configuration
声明这是一个注解类,替换原来的xml文件
ComponentScan
扫描指定包及其子包的component组件(conponent,controller,service,repository)
includeFilters 包含过滤的信息
excludeFilters 排除过滤的信息
过滤的类型: assignable 包含(排除) 指定的类
annocation 包含(排除) 指定的注解(conponent,controller,service,repository)
aspectj 指定一个切入点表达式 pattern = " com.dao.* "
custom 自定义一个过滤类,必须继承 TypeFilter 接口 重写match方法
userDefaultFilters :默认使用 exculudeFilters 设置为false 使用includeFilters
Bean
将返回值作为Bean 默认id是方法名 可以指定name属性设值
scope
两种取值 singleton 单例模式 默认 在创建applicationContext 工厂是创建对象
prototype 多例模式 默认 在获取对象 getBean()方法调用时创建
ConfigurableBeanFactory 定义在这个内中
lazy
懒加载 采用singleton 单例模式是,可以添加,使其在调用是才创建
/**
* Whether lazy initialization should occur.
*/
boolean value() default true;
//声明这是一个注解类,替换原来的xml文件
@Configuration
@ComponentScan(value = "it",includeFilters = {
//@ComponentScan.Filter(type = FilterType.ANNOTATION,classes = {Controller.class}),
//@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,classes = {PersonDaoImpl.class})
//@ComponentScan.Filter(type = FilterType.ASPECTJ,pattern = "com.dao.*")
//自定义过滤类型
@ComponentScan.Filter(type = FilterType.CUSTOM,classes = {MyfilterType.class})
},useDefaultFilters = false)
public class config01 {
@Bean(name = "person01")
@Scope
@Lazy
public Person person(){
return new Person("zhangsan",18);
}
}
conditional
根据条件判断是否 创建 当前Bean
条件类必须要继承 Condition 接口
@Configuration
@ComponentScan(basePackages = "it.itcast.config")
public class config02 {
@Bean(name = "person")
public Person person(){
return new Person("zhangsan",18);
}
@Bean(name = "bill")
@Conditional(windowConditional.class)
public Person person01(){
return new Person("bill",18);
}
@Conditional(linuxConditional.class)
@Bean(name = "linus")
public Person person02(){
return new Person("linus",18);
}
}
实现Condition 接口的类
public class linuxConditional implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
//获取当前环境
Environment environment = context.getEnvironment();
//获取当前操作系统名字
String property = environment.getProperty("os.name");
//判断是否包含"linux" 包含返回true
if(property.contains("linux")){
return true;
}
return false;
}
}
import
第一种方式:传入一个class对象,直接创建一个对象 id默认为全类名
第二种方式:传入一个 importSelector的实现类,创建 selectImports() 方法中返回的数组中包含的对象 id默认为全类名
@Configuration
@ComponentScan(value = "it",includeFilters = {
@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,classes = {PersonDaoImpl.class}),
},useDefaultFilters = false)
@Import({Red.class, MyimportSelector.class})
public class config01 {
public Person person(){
return new Person("zhangsan",18);
}
}
importSelector 实现类
public class MyimportSelector implements ImportSelector{
/**
* 返回值,就是导入到容器中的组件全类名
* AnnocationMetadata :可以获取当前标注@import类的所有注解信息
*/
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
return new String[]{"it.color.Green","it.color.Blue"};
}
@Override
public Predicate<String> getExclusionFilter() {
return null;
}
}