pring 几个扩展点
___________________________BeanPostProcesser___________________________
bean初始化时触发
在bean依赖装配(设置完成后)完成触发
这里可以指定Bean做一些处理,比如返回该对象的代理对象
@Component
public class EchoBeanPostProcesser implements BeanPostProcessor {
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("≈≈≈≈≈≈≈≈≈>>>属性设置之后,init之前"+bean.getClass());
if(bean instanceof User)
return new LogUser();
return bean;
}
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("≈≈≈≈≈≈≈≈≈>>>属性设置之后,init之后"+bean.getClass());
return bean;
}
}
___________________________BeanFactoryPostProcessor___________________________
容器初始化时触发
@Component
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
System.out.println(beanFactory.getBeanDefinitionCount());
}
}
BeanFactoryPostProcessor在Spring容容器初始化之后触发,且只能触发一次
触发时机BeanPostProcessor早
___________________________BeanDefinitRegistryPostProcessor___________________________
bean的静态注册
@Component
public class MyBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
// TODO Auto-generated method stub
}
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
for(int i=0;i<10;i++) {
BeanDefinitionBuilder bdb=BeanDefinitionBuilder.rootBeanDefinition(User.class);//bean的定义BeanDefinitionBuilder
bdb.addPropertyValue("name", "admin"+i);
registry.registerBeanDefinition("user"+i, bdb.getBeanDefinition());
}
}
}
可以拿到ConfigurableListableBeanFactory,BeanDefinitionRegistry 两个对象
BeanDefinitionRegistry 对象可以动态注入Bean
public class App {
public static void main(String[] args) {
AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext(AnnotationScan.class);
context.getBeansOfType(User.class).values().forEach(System.out::println);
context.close();
}
}