BeanPostProcess 接口
BeanPostProcess 后置处理器: 在bean 初始化前后进行一些工作
postProcessBeforeInitialization :在初始化之前调用
postProcessAfterInitialization : 在初始化之后调用
public interface BeanPostProcessor {
/**
* 在Bean初始化之前执行,即是在执行Bean的构造方法之后,在执行InitializingBean的afterPropertiesSet方法之前执行
*/
Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;
/**
* 在Bean的初始化之后执行,即是在InitializingBean的afterPropertiesSet方法之后执行
*/
Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;
}
一般ApplicationContext会自动检查是否在定义文件中有实现了BeanPostProcessor接口的类,如果有的话,Spring容器会在每个Bean(其他的Bean)被初始化之前和初始化之后,分别调用实现了BeanPostProcessor接口的类的postProcessAfterInitialization()方法和postProcessBeforeInitialization()方法,对Bean进行相关操作。
Bean的生命周期
一般情况下Bean 的生命周期如下,如果经过Aop 则会生成代理对象,并放入单例池。
BeanPostProcess 示例(自定义)
1 实体类 为了效果实现了InitalizingBean DisposableBean 在bean 创建完成赋完值后打印一些数据。
package com.boshrong.annotation.condition.entity;
import lombok.Data;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.EmbeddedValueResolverAware;
import org.springframework.util.StringValueResolver;
@Data
public class Person implements InitializingBean, DisposableBean {
String name;
String age;
public Person(String bill_gates, String s) {
}
public void destroy() throws Exception {
System.out.println("在bean 销毁的时候调用");
}
public void afterPropertiesSet() throws Exception {
System.out.println("在bean创建完成并赋完属性值之后调用");
}
}
2 定义自己的后置处理器 实现了BeanPostProcessor接口
package com.boshrong.annotation.condition.config;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
@Component
public class myBeanPostProcess implements BeanPostProcessor {
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("postProcessBeforeInitialization"+bean+"===>"+beanName);
return bean;
}
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("postProcessAfterInitialization"+bean+"===>"+beanName);
return bean;
}
}
3 配置类
package com.boshrong.annotation.condition.config;
import com.boshrong.annotation.condition.conditionmatch.Linux;
import com.boshrong.annotation.condition.entity.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("com.boshrong.annotation.condition")
public class myConfig {
@Bean("linux")
public Person person1(){
return new Person("linux","35");
}
}
4 测试类
package com.boshrong.annotation.condition.test;
import com.boshrong.annotation.condition.config.myConfig;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
public class IocTest {
AnnotationConfigApplicationContext annotationConfigApplicationContext=new AnnotationConfigApplicationContext(myConfig.class);
@Test
public void testIoc(){
printBeans(annotationConfigApplicationContext);
}
private void printBeans(AnnotationConfigApplicationContext applicationContext){
String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();
for(String name:beanDefinitionNames){
System.out.println(name);
}
}
}
运行结果展示
可以发现在afterPropertiesSet() 调用之前调用了postProcessBeforeInitialization, 之后调用了 postProcessAfterInitialization。
BeanPostProcess 作用
在Bean的初始化前后做一些自己的逻辑处理,比如为Bean设置一些额外的属性。
1 最典型的例子就是spring中的Aware接口的实现,都是利用BeanPostProcessor
在Bean初始化之前进行调用set方法设置相应的属性。
注意:xxxAware 功能的使用是使用xxxProcessor 来处理的
eg: ApplicationContextAware==>ApplicationContextAwareProcessor。
/*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.context.support;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedAction;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.EmbeddedValueResolver;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.EmbeddedValueResolverAware;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.lang.Nullable;
import org.springframework.util.StringValueResolver;
/**
* {@link BeanPostProcessor} implementation that supplies the {@code ApplicationContext},
* {@link org.springframework.core.env.Environment Environment}, or
* {@link StringValueResolver} for the {@code ApplicationContext} to beans that
* implement the {@link EnvironmentAware}, {@link EmbeddedValueResolverAware},
* {@link ResourceLoaderAware}, {@link ApplicationEventPublisherAware},
* {@link MessageSourceAware}, and/or {@link ApplicationContextAware} interfaces.
*
* <p>Implemented interfaces are satisfied in the order in which they are
* mentioned above.
*
* <p>Application contexts will automatically register this with their
* underlying bean factory. Applications do not use this directly.
*
* @author Juergen Hoeller
* @author Costin Leau
* @author Chris Beams
* @since 10.10.2003
* @see org.springframework.context.EnvironmentAware
* @see org.springframework.context.EmbeddedValueResolverAware
* @see org.springframework.context.ResourceLoaderAware
* @see org.springframework.context.ApplicationEventPublisherAware
* @see org.springframework.context.MessageSourceAware
* @see org.springframework.context.ApplicationContextAware
* @see org.springframework.context.support.AbstractApplicationContext#refresh()
*/
class ApplicationContextAwareProcessor implements BeanPostProcessor {
private final ConfigurableApplicationContext applicationContext;
private final StringValueResolver embeddedValueResolver;
/**
* Create a new ApplicationContextAwareProcessor for the given context.
*/
public ApplicationContextAwareProcessor(ConfigurableApplicationContext applicationContext) {
this.applicationContext = applicationContext;
this.embeddedValueResolver = new EmbeddedValueResolver(applicationContext.getBeanFactory());
}
@Override
@Nullable
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (!(bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware ||
bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware ||
bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware)){
return bean;
}
AccessControlContext acc = null;
if (System.getSecurityManager() != null) {
acc = this.applicationContext.getBeanFactory().getAccessControlContext();
}
if (acc != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareInterfaces(bean);
return null;
}, acc);
}
else {
invokeAwareInterfaces(bean);
}
return bean;
}
private void invokeAwareInterfaces(Object bean) {
if (bean instanceof EnvironmentAware) {
((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
}
if (bean instanceof EmbeddedValueResolverAware) {
((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver);
}
if (bean instanceof ResourceLoaderAware) {
((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
}
if (bean instanceof ApplicationEventPublisherAware) {
((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
}
if (bean instanceof MessageSourceAware) {
((MessageSourceAware) bean).setMessageSource(this.applicationContext);
}
if (bean instanceof ApplicationContextAware) {
((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
}
}
}
根据源码可以看到通过实现后置处理器的的 postProcessBeforeInitializatio 方法,判断当前bean的类型并为其属性赋值。
2 @Autowired
的实现依赖注入也是使用的BeanPostProcessor的原理。