@PropertySource注解
@PropertySource
:加载指定的配置文件
@ConfigurationProperties默认是从全局配置文件中获取值
若不是从全局配置文件中获取值 则须加上@PropertySource
注解来指定
@PropertySource的value值还可以传入数组的方式加载多个配置文件
person.name=陈涛
person.age=19
person.isStudent=true
person.birth=2020/01/01
person.maps.k1=v111
person.maps.k2=v211
person.lists=pico,tankman
person.dog.name=dog
person.dog.age=2
用@PropertySource注解指定配置文件:
@Component
@PropertySource(value = {"classpath:person.properties"})
@ConfigurationProperties(prefix = "person")
public class Person {
private String name;
private Integer age;
private Boolean isStudent;
private Date birth;
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;
...
}
@Autowired
private Person person;
@Test
void contextLoads() {
System.out.println(person);
}
测试成功
@ImportResource注解
@ImportResource
:导入Spring的配置文件 让配置文件中的内容生效
SpringBoot中没有Spring的配置文件 且自己编写的配置文件也不能够被自动识别
若想让Spring的配置文件生效 加载进ioc容器 则需要将@ImportResource
注解标注在一个配置类上(主配置类 即启动类也可)
用于测试的配置文件:
<?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="net.zjitc.springboot.service.HelloService"/>
</beans>
开始测试:
@Autowired
ApplicationContext ioc;
@Test
public void testHelloService()
{
System.out.println(ioc.containsBean("helloService"));
}
结果:false
添加@ImportResource
注解并指定Spring配置文件的路径:
@ImportResource(locations = {"classpath:beans.xml"})
@SpringBootApplication
public class SpringbootConfigYmlApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootConfigYmlApplication.class, args);
}
}
结果:true