技巧:
1、processor 处理技巧
2、chain 模式
3、代理模式 + 建造模式
一、spring 的 bean 对象是如何生成的,其中有哪些扩展点 ?
image.pngClassPathXmlApplicationContext对象:
image.png
二、常见的扩展点
1、BeanFactoryPostProcessor
常见实现:PropertyResourceConfigurer、CustomEditorConfigurer
2、BeanPostProcessor
InstantiationAwareBeanPostProcessor
常见实现:AutowiredAnnotationBeanPostProcessor
3、ImportBeanDefinitionRegistrar
三、基础的API
DefaultListableBeanFactory beanfactory = new DefaultListableBeanFactory();
//设置BeanFactoryPostProcessor处理器
PropertyPlaceholderConfigurer propertyPlaceholderConfigurer = beanfactory.getBean(PropertyPlaceholderConfigurer.class);
propertyPlaceholderConfigurer.postProcessBeanFactory(beanfactory);
//设置BeanPostProcessor处理器
AutowiredAnnotationBeanPostProcessor autowiredAnnotationBeanPostProcessor = new AutowiredAnnotationBeanPostProcessor();
autowiredAnnotationBeanPostProcessor.setBeanFactory(beanfactory);
beanfactory.addBeanPostProcessor(autowiredAnnotationBeanPostProcessor);
//加载 bean 资源
Resource res = new ClassPathResource("spring-bean.xml");
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanfactory);
reader.loadBeanDefinitions(res);
//获取 Bean 对象
Worker worker = beanfactory.getBean("worker", Worker.class);
高级 API:
1、动态注册 Bean 对象
BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(User.class);
beanDefinitionBuilder.addPropertyValue("name", "1");
beanDefinitionBuilder.addPropertyValue("age", "2");
BeanDefinition beanDefinition = beanDefinitionBuilder.getBeanDefinition();
beanfactory.registerBeanDefinition("people", beanDefinition );
User user = beanfactory.getBean("people", User.class);
网友评论