@Configuration
通过配置文件注入类,properties可以完成springboot大部分bea配置, 但是这不代表所有Bean能够被配置,这个时候需要用到@Configuration+@Bean或者@Configuration+@Component。@Configuration 注解类等价与 XML中配置 beans,用@Bean 注解方法等价于 XML 中配置 bean。
下面举例说明2中配置方法:
1. @Configuration+@Bean
1.1BeanTest类:
public class BeanTest {
private Logger logger = LoggerFactory.getLogger(BeanTest.class);
public void test(){
logger.info("BeanTest is going..........");
}
}
1.2 ConfigurationInfo类
@Configuration
public class ConfigurationInfo {
private Logger logger = LoggerFactory.getLogger(ConfigurationInfo.class);
public ConfigurationInfo(){
logger.info("ConfigurationInfo with Configuration....");
}
@Bean
public BeanTest testBean() {
return new BeanTest();
}
}
1.3 单元测试用例
@Test
public void testConfiguration(){
logger.info("testConfiguration in.......");
ApplicationContext context = new AnnotationConfigApplicationContext(ConfigurationInfo.class);
BeanTest mBeanTest = (BeanTest) context.getBean("testBean");
mBeanTest.test();
}
1.4 测试结果:
2. @Configuration+@Component
2.1 BeanComponentTest类
扫描二维码关注公众号,回复:
8950709 查看本文章
![](/qrcode.jpg)
@Component
public class BeanComponentTest {
private Logger logger = LoggerFactory.getLogger(BeanComponentTest.class);
public void test(){
logger.info("BeanComponentTest is going..........");
}
}
2.2 ConfigurationComponentInfo 类,要扫描Bean的位置
@Configuration
@ComponentScan(basePackages = "com.test.annotaton.bean")
public class ConfigurationComponentInfo {
private Logger logger = LoggerFactory.getLogger(ConfigurationComponentInfo.class);
public ConfigurationComponentInfo(){
logger.info("ConfigurationComponentInfo with Configuration....");
}
}
2.3 单元测试类
@Test
public void testConfigComponent(){
logger.info("testConfigComponent in.......");
ApplicationContext context = new AnnotationConfigApplicationContext(ConfigurationComponentInfo.class);
BeanComponentTest mBeanComponentTest = (BeanComponentTest) context.getBean("beanComponentTest");
mBeanComponentTest.test();
}
2.4 测试结果