1.@Configuration 表明该类为配置类
2.@Bean 给容器注入一个Bean 相当于<bean>标签
3.@ComponentScan(value="com.xxx",excludeFilters="com.xxx.service",includeFilters="com.xxx.impl") value指定要扫描的包
相当于
<context:component-scan base-package="com.gdsp">
<context:include-filter type="annotation" expression="com.xxx.impl"/>
<context:exclude-filter type="annotation" expression="com.xxx.service"/>
同样
@Filter(type=FilterType.ANNOTATION,classes={Controller.class}),
@Filter(type=FilterType.ASSIGNABLE_TYPE,classes={BookService.class})
4.@Scope:调整作用域
prototype:多实例的:ioc容器启动并不会去调用方法创建对象放在容器中。每次获取的时候才会调用方法创建对象;
singleton:单实例的(默认值):ioc容器启动会调用方法创建对象放到ioc容器中。以后每次获取就是直接从容器中拿
request:同一次请求创建一个实例
session:同一个session创建一个实例
5.@Conditional 根据条件进行判断。满足条件给容器中注册bean
public class WindowsCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
Environment environment = context.getEnvironment();
String property = environment.getProperty("os.name");
if(property.contains("Windows")){
return true;
}
return false;
}
}
@Conditional({WindowsCondition.class})
public class MainConfig{... ...}
6.@Import(被导入的组件全类名)导入组件
ImportSelector:返回需要导入的组件的全类名数组;
ImportBeanDefinitionRegistrar:手动注册bean到容器中
public class MyImportSelector implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
ֵ
return new String[]{"com.xxx.service.A","com.xxx.impl.B"};
}
}
public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
boolean definition = registry.containsBeanDefinition("com.xxx.service.A");
boolean definition2 = registry.containsBeanDefinition("com.xxx.impl.B");
if(definition && definition2){
RootBeanDefinition beanDefinition = new RootBeanDefinition(RainBow.class);
registry.registerBeanDefinition("rainBow", beanDefinition);
}
}
}
7.使用Spring提供的 FactoryBean(工厂Bean);
默认获取到的是工厂bean调用getObject创建的对象
要获取工厂Bean本身,我们需要给id前面加一个&
public class ColorFactoryBean implements FactoryBean<Color> {
@Override
public Color getObject() throws Exception {
return new Color();
}
@Override
public Class<?> getObjectType() {
return Color.class;
}
@Override
public boolean isSingleton() {
return false;
}
}