spring实战之javaconfig
所属分类 spring
浏览量 1356
JavaConfig 在 java 中配置 bean
Spring3.0开始 ,@Configuration用于定义配置类,可替换xml配置文件,
配置类内部包含有一个或多个被@Bean注解的方法,
AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext
配置类引用 其他配置类 或 xml 配置
@Import(TestConfiguration.class)
@ImportResource("classpath:applicationContext-configuration.xml")
Bean1 添加 @Component
Bean2 在 Config2中定义
Bean3 在 Config3中定义
Bean1.java
@Component
public class Bean1{
public Bean1(){
System.out.println(this+" create "+new Date());
}
}
Config2.java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class Config2{
@Bean
public Bean2 bean2(){
return new Bean2();
}
}
Config1.java
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
// @ComponentScan(useDefaultFilters = false,includeFilters = {@Filter(type = FilterType.ANNOTATION, value = Component.class)})
// @ComponentScan(useDefaultFilters = false,includeFilters = {@Filter(type = FilterType.CUSTOM, value = MyTypeFilter.class)})
@ComponentScan(useDefaultFilters = true,excludeFilters = {@Filter(type = FilterType.ANNOTATION, value = Configuration.class)})
@Configuration
public class Config1{
}
Hello.java
// AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Config1.class);
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(Config1.class);
// ctx.register(Config2.class);
// ctx.register(Config3.class);
ctx.refresh();
Config1 中 使用 @ComponentScan ,才能扫描到 Bean1 Config2 Config3
排除对 Config2 Config3 的扫描
@ComponentScan(useDefaultFilters = true,excludeFilters = {@Filter(type = FilterType.ANNOTATION, value = Configuration.class)})
完整代码
https://gitee.com/dyyx/hellocode/tree/master/project/springtest/src/main/java/dyyx/javaconfig
上一篇
下一篇
使用jar命令生成jar包
spring资源加载机制
spring组件扫描
jar包冲突的处理套路
spring注解之@Value
金融圈饭局老司机火眼金睛识人