一、@PropertySource
1、定義
自定義配置文件名稱,多用于配置文件與實(shí)體屬性映射。
2、使用
上一章節(jié)我們介紹了如何從配置文件里獲取值,與JavaBean做映射。但是存在的問題是我們是從主配置(application.yml)里讀取的。如果全部的配置都寫到application里,那就亂套了。所以我們可以按照不同模塊自定義不同的配置文件。
2.1、配置
person.properties
person.lastName=李四
person.age=25
person.birth=2017/12/15
person.boss=true
person.maps.key1=value1
person.maps.key2=value2
person.lists=a,b,c
person.dog.name=dog
person.dog.age=2
2.2、JavaBean
@PropertySource(value = {"classpath:person.properties"})
@ConfigurationProperties(prefix = "person")
@Component
public class Person {
private String lastName;
private Integer age;
private boolean isBoss;
private Date birth;
private Map<String, Object> maps;
private List<Object> lists;
private Dog dog;
...setter/getter/toString...
}
這樣一個(gè)注解(@PropertySource(value = {"classpath:person.properties"})
)就可以搞定不在主配置里讀取,按照不同的功能模塊劃分出不同的配置文件。
二、@ImportResource
1、定義
將外部的配置文件加載到程序中來,比如我們定義一個(gè)beans.xml
文件,里面配置了一個(gè)bean,默認(rèn)情況下這個(gè)bean是不會(huì)加載到Spring容器中來的。我們需要@ImportResource注解將這個(gè)配置文件加載進(jìn)來。
2、使用
2.1、配置
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.chentongwei.springboot.service.HelloService"></bean>
</beans>
2.2、JavaBean
public class HelloService {}
2.3、測(cè)試類
@RunWith(SpringRunner.class)
@SpringBootTest
public class Springboot02ConfigApplicationTests {
@Autowired
private ApplicationContext ioc;
@Test
public void testHelloService() {
boolean helloService = ioc.containsBean("helloService");
System.out.println(helloService);
}
}
2.4、測(cè)試結(jié)果
false
2.5、修改運(yùn)行類
@SpringBootApplication
@ImportResource(locations = {"classpath:beans.xml"})
public class Springboot02ConfigApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot02ConfigApplication.class, args);
}
}
2.6、測(cè)試結(jié)果
true
PS:因?yàn)槲覀儗⑼獠康呐渲梦募肓耍珸ImportResource(locations = {"classpath:beans.xml"})
2.7、注意
@ImportResource這么看的話沒卵用,因?yàn)槲覀儸F(xiàn)在都沒了配置文件了,所以引入什么呢?其實(shí)并不然,比如:dubbo還是需要靠配置文件來配置bean的,這時(shí)候就需要此注解了。(我知道dubbo也可以按照注解來配置,我只是舉個(gè)例子。),若只為了注入一個(gè)bean,完全可以采取Spring的@Bean注解。
三、廣告
QQ群【Java初學(xué)者學(xué)習(xí)交流群】:458430385
微信公眾號(hào)【Java碼農(nóng)社區(qū)】
img
- 今日頭條號(hào):編程界的小學(xué)生