SpringBoot_@PropertiesSource,@ImportResource,@Bean
原创
©著作权归作者所有:来自51CTO博客作者959_1x的原创作品,请联系作者获取转载授权,否则将追究法律责任
@Properties:记载指定的配置文件
比如如果要加载person.properties
需要在实体类Person上加上@PropertiesSource注解
@ImportResource:给容器添加组件
如果是添加了一个beans.xml
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">
需要在运行类中加上
@ImportResource(locations = {“classpath:beans.xml”})
利用SpringBoot单元测试一下
@Autowired
ApplicationContext ioc;
@Test
public void test2(){
boolean helloService = ioc.containsBean("helloService");
System.out.println(helloService);
}
结果为true.就是说beans,xml组件在容器里添加了
@Bean给容器添加配置类
MyAppConfig.java
@Configuration//指明当前是一个配置类,替代之前的Spring配置文件
public class MyAppConfig {
@Bean
public HelloService helloService(){
System.out.println("1");
return new HelloService();
}
}
运用SpringBoot的单元测试
@Autowired
ApplicationContext ioc;
@Test
public void test2(){
boolean helloService = ioc.containsBean("helloService");
System.out.println(helloService);
}
添加到容器的组件中
指明当前是一个配置类,替代之前的Spring配置文件
最后加上Bean的注解也是SpringBoot推荐的一种添加到容器组件的方法