spring beanFactory后置处理器-BeanFactoryPostProcessor

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

定义一个单例bean

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


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

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

自定义实现该接口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());
	}
}

这样就完成的对于bean的作用域变化,但是这个地方是将自定义的TestBeanFactoryPostProcessor交给了spring管理

如果我们不想呢,当然如果了解@Import这个注解用法的人可能有个大胆的想法,通过自定义注解灵活开启该处理器的功能。

首先我们去掉该类交给spring管理的注解@Component,添加自定义注解

@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());
	}
}

配置类添加我们的自定义注解来灵活开启

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

猜你喜欢

转载自blog.csdn.net/qq_38108719/article/details/100591053
今日推荐