Spring中BeanFactoryPostProcessors理解
1.BeanFactoryPostProcessors理解
BeanFactoryPostProcessors 就是对BeanDefinition进行加强
1.spring扫描所有的class类,并封装成BeanDefinition
2.BeanFactoryPostProcessors可以对BeanDefinition修改
3.spring后续会根据BeanDefinition完成对bean的初始化
这个invokeBeanFactoryPostProcessors实现对我们的class类加载到BeanDefinition
org.springframework.context.support.AbstractApplicationContext
调用前
调用后
把新的两个class加载到BeanDefinition
2.BeanFactoryPostProcessors实战运用
2.1 目录结构
2.2 代码
普通的StudentService对象
package com.my.study.test.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class StudentService {
public void study(){
System.out.println("student is studying");
}
}
TeacherService 对象,但是加@Component
package com.my.study.test.service;
import org.springframework.beans.factory.annotation.Autowired;
public class TeacherService {
public void teaching(){
System.out.println("teacher is teaching");
}
}
实现BeanFactoryPostProcessor 接口,并对StudentService 的beanDefinition修改
package com.my.study.test.service;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;
@Component
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
BeanDefinition beanDefinition = beanFactory.getBeanDefinition("studentService");
System.out.println(beanDefinition.getBeanClassName());
beanDefinition.setBeanClassName(TeacherService.class.getName());
}
}
AppConfig 作为一个config包,表明要扫描哪些class
@ComponentScan("com.my.study.test.service")
public class AppConfig {
}
测试类
package com.my.study.test;
import com.my.study.test.service.TeacherService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Test {
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
TeacherService teacherService = applicationContext.getBean(TeacherService.class);
teacherService.teaching();
}
}