spring beanFactory post processor-BeanFactoryPostProcessor

spring-BeanFactoryPostProcessor有什么功能呢。他能改变bean在实例化之前的一些原注解值,比如单例变原型,手动减轻BeanFactory的工作压力。
原注解是指spring默认为bean装配的注解比如:@Scope,@lazy,@Primary,@DependsOn,@Role,@Description
直接看代码

Define a singleton bean

@Component
@Scope("singleton")
public class Teacher{


	public Teacher(){
		System.out.println("Construct");
	}

	@PostConstruct
	public void init(){
		System.out.println("init");
	}
}

Customize the processor that implements the interface BeanFactoryPostProcessor

@Component
public class TestBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
		BeanDefinition beanDefinition = beanFactory.getBeanDefinition("teacher");
		beanDefinition.setScope("prototype");
		System.out.println("Scope:"+beanDefinition.getScope());
	}
}

This completes the scope change of the bean, but this place is to give the custom TestBeanFactoryPostProcessor to spring management

If we don't want to, of course, people who understand the usage of @Import may have a bold idea to enable the function of the processor flexibly through custom annotations.

First, we remove the annotation @Component that the class has handed over to spring to manage, and add a custom annotation

@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(TestBeanFactoryPostProcessor.class)
public @interface TestBeanFactoryPostProcessorAnno {
}

public class TestBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
		BeanDefinition beanDefinition = beanFactory.getBeanDefinition("teacher");
		beanDefinition.setScope("prototype");
		System.out.println("Scope:"+beanDefinition.getScope());
	}
}

 

Add our custom annotations to the configuration class to open it flexibly

@Configuration
//@Import(TestImportSelector.class)
//@TestImportSelectorAnno
@TestBeanFactoryPostProcessorAnno
@ComponentScan("org.springframework.test.main.*")
public class ScanConfig {
}
@Configuration这个注解加与不加程序一样能完整跑下去,但是加与不加有什么区别呢,我们后期再提。

Guess you like

Origin blog.csdn.net/qq_38108719/article/details/100591053