一、 @PropertySource
正常情况下@ConfigurationProperties读取的是全局配置文件(工程创建成功后自带的application.properties文件),假如我的javaBean相关的配置不在全局配置文件中配置,而是在自己写的局部配置文件中,此时就要用到@PropertySource来加载指定的配置文件。例如我将之前在全局配置文件中写的配置信息注释,在自己新建的一个配置文件中重新配置,person.properties的配置信息如下:
#配置person的值
person.last-name=李四
person.age=18
person.birth=2017/12/15
person.boss=false
person.maps.k1=v1
person.maps.k2=14
person.lists=a,b,c
person.dog.name=guang
person.dog.age=26
在javaBean中使用时,可以这样使用:
@PropertySource(value = {"classpath:person.properties"})
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
// @Value("${person.last-name}")
private String lastName;
// @Value("${person.age}")
private Integer age;
private Boolean boss;
private Date birth;
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;
二、@ImportSource
导入Spring的配置文件,让配置文件的内容生效。
这里写了一个spring的beans.xml配置文件,内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="helloService" class="com.atguigu.springboot.service.HelloService"></bean>
</beans>
为了让此配置文件生效,我们需要将@ImportSource标注在一个配置类上,这里标注在主配置类上,即在SpringBootApplication中加上注解@ImportSource,如下所示:
@ImportResource(locations = {"classpath:beans.xml"})
@SpringBootApplication
public class SpringBoot02ConfigApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBoot02ConfigApplication.class, args);
}
}
SpringBoot推荐给容器中添加组件的方式:推荐使用全注解的方式
1、写一个配置类=======Spring配置文件
配置类MyAppConfig 的内容:
/**
* @Configuration:指明当前类是一个配置类,替代之前的Spring配置文件
*/
@Configuration
public class MyAppConfig {
//@Bean:将方法的返回值添加到容器中,容器中这个组件默认的id就是方法名
@Bean
public HelloService helloService(){
System.out.println("配置类@Bean给容器中添加组件成功");
return new HelloService();
}
}
完整代码见:
https://github.com/13029403279/Study/upload/master
下的spring-boot-config