精华内容
下载资源
问答
  • Spring后置处理器

    2016-08-04 20:47:14
    Spring后置处理器


    <bean id="newperson"class="cm.xls.czq.spring.NewPerson" init-method="init"destroy-method="destory">

    init-method="init" 初始化的方法

    destroy-method="destory"销毁前的方法

     

    后置处理器是可以配置在初始化前后的方法:

    1.        继承BeanPostProcessor接口

    初始化前

    public ObjectpostProcessAfterInitialization(Object bean, String beanName) throws BeansException;

    初始化后

    public Object postProcessBeforeInitialization(Object bean, String beanName)

     

             在bean.xml在新建一个bean

    <bean class="cm.xls.czq.spring.MyBeanPostProcessor"></bean>

    展开全文
  • spring后置处理器

    千次阅读 2019-01-12 14:27:09
    bean的后置处理器,主要在bean初始化前后工作。接口定义: public interface BeanPostProcessor { // 在初始化方法(如:afterPropertiesSet 或 init-method)执行前触发 @Nullable default Object ...

    1. BeanPostProcessor

    bean的后置处理器,主要在bean初始化前后工作。接口定义:

    public interface BeanPostProcessor {
    
    	// 在初始化方法(如:afterPropertiesSet 或 init-method)执行前触发
    	@Nullable
    	default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    		return bean;
    	}
    
    	// 在初始化方法(如:afterPropertiesSet 或 init-method)执行后触发
    	@Nullable
    	default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    		return bean;
    	}
    
    }
    

    2. InstantiationAwareBeanPostProcessor

    InstantiationAwareBeanPostProcessor继承于BeanPostProcessor,主要在实例化bean前后工作; AOP创建代理对象就是通过该接口实现。接口定义:

    public interface InstantiationAwareBeanPostProcessor extends BeanPostProcessor {
    
    	// 对象实例化前
    	@Nullable
    	default Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
    		return null;
    	}
    
    	// 对象实例化后
    	default boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
    		return true;
    	}
    
    	@Nullable
    	default PropertyValues postProcessPropertyValues(
    			PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException {
    
    		return pvs;
    	}
    
    }
    

    3. BeanFactoryPostProcessor

    bean工厂的后置处理器,在bean定义(bean definitions)加载完成后,bean尚未初始化前执行。接口定义:

    public interface BeanFactoryPostProcessor {
    
    	/**
    	 * Modify the application context's internal bean factory after its standard
    	 * initialization. All bean definitions will have been loaded, but no beans
    	 * will have been instantiated yet. This allows for overriding or adding
    	 * properties even to eager-initializing beans.
    	 * @param beanFactory the bean factory used by the application context
    	 * @throws org.springframework.beans.BeansException in case of errors
    	 */
    	void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;
    
    }
    

    4. BeanDefinitionRegistryPostProcessor

    BeanDefinitionRegistryPostProcessor继承于BeanFactoryPostProcessor。其自定义的方法postProcessBeanDefinitionRegistry会在bean定义(bean definitions)将要加载,bean尚未初始化前真执行,即在BeanFactoryPostProcessor的postProcessBeanFactory方法前被调用。接口定义:

    public interface BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor {
    
    	/**
    	 * Modify the application context's internal bean definition registry after its
    	 * standard initialization. All regular bean definitions will have been loaded,
    	 * but no beans will have been instantiated yet. This allows for adding further
    	 * bean definitions before the next post-processing phase kicks in.
    	 * @param registry the bean definition registry used by the application context
    	 * @throws org.springframework.beans.BeansException in case of errors
    	 */
    	void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException;
    
    }
    
    展开全文
  • spring 后置处理器

    2019-06-26 14:48:03
    spring 中的注解,比如...在spring中,有提供一类特殊的接口,叫做后置处理器 这类接口提供给处理类,可以修改bean的值,或者在bean实例化过程中添加其他处理: public interface BeanFactoryPostProcessor { ...

    spring 中的注解,比如@Autowired 、dubbo的@AutowiredDubbo,还有@Value等等的使用,是如何完成依赖注入的?

    在spring中,有提供一类特殊的接口,叫做后置处理器

     这类接口提供给处理类,可以修改bean的值,或者在bean实例化过程中添加其他处理:

     

    public interface BeanFactoryPostProcessor {
        void postProcessBeanFactory(ConfigurableListableBeanFactory var1) throws BeansException;
    }
    public interface BeanPostProcessor {
        Object postProcessBeforeInitialization(Object var1, String var2) throws BeansException;
    
        Object postProcessAfterInitialization(Object var1, String var2) throws BeansException;
    }
    

     接下来分析一下后置处理器的使用。

     apollo在项目中的使用:

    @SpringBootApplication
    @ComponentScan(basePackages = (MobileOfficeApplication.keKeingPackages))
    @EnableAspectJAutoProxy(proxyTargetClass = true, exposeProxy = true)
    @EnableJpaAuditing
    @EnableApolloConfig
    @EnableDubbo
    @EnableAsync
    @EntityScan({MobileOfficeApplication.keKeingPackages})
    @EnableFeignClients(basePackages = (MobileOfficeApplication.keKeingPackages))
    public class MobileOfficeApplication {
    
        static final String keKeingPackages = "cn.*.*";
    
        public static void main(String[] args) {
            SpringApplication.run(MobileOfficeApplication.class, args);
        }
    
    
    }

     

    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.TYPE})
    @Documented
    @Import({ApolloConfigRegistrar.class})
    public @interface EnableApolloConfig {
        String[] value() default {"application"};
    
        int order() default 2147483647;
    }
    

     看这里的注解@Import({ApolloConfigRegistrar.class}),import注解用于引入bean,ApolloConfigRegistrar对象是apollo包下的。

    public class ApolloConfigRegistrar implements ImportBeanDefinitionRegistrar {
        public ApolloConfigRegistrar() {
        }
    
        public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
            AnnotationAttributes attributes = AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(EnableApolloConfig.class.getName()));
            String[] namespaces = attributes.getStringArray("value");
            int order = (Integer)attributes.getNumber("order");
            PropertySourcesProcessor.addNamespaces(Lists.newArrayList(namespaces), order);
            BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, PropertySourcesPlaceholderConfigurer.class.getName(), PropertySourcesPlaceholderConfigurer.class);
            BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, PropertySourcesProcessor.class.getName(), PropertySourcesProcessor.class);
            BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, ApolloAnnotationProcessor.class.getName(), ApolloAnnotationProcessor.class);
            BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, SpringValueProcessor.class.getName(), SpringValueProcessor.class);
            BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, SpringValueDefinitionProcessor.class.getName(), SpringValueDefinitionProcessor.class);
            BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, ApolloJsonValueProcessor.class.getName(), ApolloJsonValueProcessor.class);
        }
    }

     registerBeanDefinitions方法中会注册多个对象,这些对象是用来做什么的呢?

    public class SpringValueProcessor extends ApolloProcessor implements BeanFactoryPostProcessor 

     查看apollo源码

    public abstract class ApolloProcessor implements BeanPostProcessor, PriorityOrdered {
    public class PropertySourcesProcessor implements BeanFactoryPostProcessor, EnvironmentAware, PriorityOrdered 
    public class ApolloJsonValueProcessor extends ApolloProcessor implements BeanFactoryAware 
    public class SpringValueDefinitionProcessor implements BeanDefinitionRegistryPostProcessor
    public class SpringValueProcessor extends ApolloProcessor implements BeanFactoryPostProcessor 
    public class ApolloAnnotationProcessor extends ApolloProcessor
    public class PropertySourcesPlaceholderConfigurer extends PlaceholderConfigurerSupport implements EnvironmentAware

     apollo注册的bean对象,都有继承或者实现spring提供的接口。

     BeanFactoryPostProcessor和BeanPostProcessor这两个接口都是初始化bean时对外暴露的入口之一,BeanFactoryPostProcessor是bean工厂的bean属性处理容器,说通俗一些就是可以管理我们的bean工厂内所有的beandefinition(未实例化)数据,可以随心所欲的修改属性。

    apollo功能最重要的一点就是动态的修改对象属性,那看到这里应该都会猜想功能的实现是跟BeanFactoryPostProcessor这个接口有关。

    processField方法有处理Value注解,具体apollo的逻辑以后再细心研读分享一下。

    protected void processField(Object bean, String beanName, Field field) {
            Value value = (Value)field.getAnnotation(Value.class);
            if (value != null) {
                Set<String> keys = this.placeholderHelper.extractPlaceholderKeys(value.value());
                if (!keys.isEmpty()) {
                    Iterator var6 = keys.iterator();
    
                    while(var6.hasNext()) {
                        String key = (String)var6.next();
                        SpringValue springValue = new SpringValue(key, value.value(), bean, beanName, field, false);
                        this.springValueRegistry.register(key, springValue);
                        logger.debug("Monitoring {}", springValue);
                    }
    
                }
            }
        }

    AutowiredDubbo处理相关代码: 

    @Configuration
    @ConditionalOnBean(
        annotation = {EnableDubbo.class}
    )
    @EnableConfigurationProperties({DubboConfiguration.class})
    public class ConsumerAutoConfiguration implements BeanPostProcessor {
        private Logger logger = LoggerFactory.getLogger(ConsumerAutoConfiguration.class);
        private Map<String, Object> refrences = new ConcurrentHashMap();
        @Autowired
        private ApplicationContext applicationContext;
        @Autowired
        private DubboConfiguration configuration;
    
        public ConsumerAutoConfiguration() {
        }
    
        public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
            Object current = bean;
            Class<?> clazz = bean.getClass();
            if (AopUtils.isAopProxy(bean)) {
                clazz = AopUtils.getTargetClass(bean);
            }
    
            try {
                if (AopUtils.isCglibProxy(bean)) {
                    current = getCglibProxyTargetObject(bean);
                } else if (AopUtils.isJdkDynamicProxy(bean)) {
                    current = getJdkDynamicProxyTargetObject(bean);
                }
            } catch (Exception var21) {
                this.logger.error("", var21);
            }
    
            try {
                Field[] var5 = clazz.getDeclaredFields();
                int var6 = var5.length;
    
                for(int var7 = 0; var7 < var6; ++var7) {
                    Field field = var5[var7];
                    AutowiredDubbo autowiredDubbo = (AutowiredDubbo)field.getAnnotation(AutowiredDubbo.class);
                    if (autowiredDubbo != null) {
                        Class<?> type = field.getType();
                        ReferenceBean<?> dubboConsumer = this.initAutowiredDubboBean(type, autowiredDubbo);
                        String group = dubboConsumer.getGroup();
                        String version = dubboConsumer.getVersion();
                        String key = type + "_" + group + "_" + version;

     

    那么后置处理又是如何生效的?

     在spring boot启动阶段,

     public void refresh() throws BeansException, IllegalStateException {
            Object var1 = this.startupShutdownMonitor;
            synchronized(this.startupShutdownMonitor) {
                this.prepareRefresh();
                ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
                this.prepareBeanFactory(beanFactory);
    
                try {
                    this.postProcessBeanFactory(beanFactory);
                    this.invokeBeanFactoryPostProcessors(beanFactory);
                    this.registerBeanPostProcessors(beanFactory);
                    this.initMessageSource();
                    this.initApplicationEventMulticaster();
                    this.onRefresh();
                    this.registerListeners();
                    this.finishBeanFactoryInitialization(beanFactory);
                    this.finishRefresh();
                } catch (BeansException var9) {
                    if (this.logger.isWarnEnabled()) {
                        this.logger.warn("Exception encountered during context initialization - cancelling refresh attempt: " + var9);
                    }
    
                    this.destroyBeans();
                    this.cancelRefresh(var9);
                    throw var9;
                } finally {
                    this.resetCommonCaches();
                }
    
            }
        }

     这里的方法就是调用所有BeanFactoryPostProcessor的postProcessBeanFactory方法:

    protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
            PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, this.getBeanFactoryPostProcessors());
            if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean("loadTimeWeaver")) {
                beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
                beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
            }
    
        }

     

     private static void invokeBeanFactoryPostProcessors(Collection<? extends BeanFactoryPostProcessor> postProcessors, ConfigurableListableBeanFactory beanFactory) {
            Iterator var2 = postProcessors.iterator();
    
            while(var2.hasNext()) {
                BeanFactoryPostProcessor postProcessor = (BeanFactoryPostProcessor)var2.next();
                postProcessor.postProcessBeanFactory(beanFactory);
            }
    
        }

    上面介绍的是 BeanFactoryPostProcessor 接口的调用过程。

    BeanPostProcessor 的实现原理跟踪:

     

      if (mbd.isSingleton()) {
                        sharedInstance = this.getSingleton(beanName, new ObjectFactory<Object>() {
                            public Object getObject() throws BeansException {
                                try {
                                    return AbstractBeanFactory.this.createBean(beanName, mbd, args);
                                } catch (BeansException var2) {
                                    AbstractBeanFactory.this.destroySingleton(beanName);
                                    throw var2;
                                }
                            }
                        });
                        bean = this.getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
                    } else if (mbd.isPrototype()) {
                        var11 = null;
    
                        Object prototypeInstance;
                        try {
                            this.beforePrototypeCreation(beanName);
                            prototypeInstance = this.createBean(beanName, mbd, args);
                        } finally {
                            this.afterPrototypeCreation(beanName);
                        }
    
                        bean = this.getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
                    }

    继续跟踪到createBean—>doCreateBean—>initializeBean

    这里看到applyBeanPostProcessorsBeforeInitialization 和applyBeanPostProcessorsAfterInitialization方法 

     protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
            if (System.getSecurityManager() != null) {
                AccessController.doPrivileged(new PrivilegedAction<Object>() {
                    public Object run() {
                        AbstractAutowireCapableBeanFactory.this.invokeAwareMethods(beanName, bean);
                        return null;
                    }
                }, this.getAccessControlContext());
            } else {
                this.invokeAwareMethods(beanName, bean);
            }
    
            Object wrappedBean = bean;
            if (mbd == null || !mbd.isSynthetic()) {
                wrappedBean = this.applyBeanPostProcessorsBeforeInitialization(bean, beanName);
            }
    
            try {
                this.invokeInitMethods(beanName, wrappedBean, mbd);
            } catch (Throwable var6) {
                throw new BeanCreationException(mbd != null ? mbd.getResourceDescription() : null, beanName, "Invocation of init method failed", var6);
            }
    
            if (mbd == null || !mbd.isSynthetic()) {
                wrappedBean = this.applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
            }
    
            return wrappedBean;
        }

     执行前置处理

     public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) throws BeansException {
            Object result = existingBean;
            Iterator var4 = this.getBeanPostProcessors().iterator();
    
            do {
                if (!var4.hasNext()) {
                    return result;
                }
    
                BeanPostProcessor beanProcessor = (BeanPostProcessor)var4.next();
                result = beanProcessor.postProcessBeforeInitialization(result, beanName);
            } while(result != null);
    
            return result;
        }

     执行后置处理

     public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException {
            Object result = existingBean;
            Iterator var4 = this.getBeanPostProcessors().iterator();
    
            do {
                if (!var4.hasNext()) {
                    return result;
                }
    
                BeanPostProcessor beanProcessor = (BeanPostProcessor)var4.next();
                result = beanProcessor.postProcessAfterInitialization(result, beanName);
            } while(result != null);
    
            return result;
        }

    我们就找到了BeanPostProcessor 的处理过程了。

    展开全文
  • Spring后置处理器BeanPostProcessor Spring提供了许多扩展点,如FactoryBean、Aware,这里还有BeanPostProcessor 在Spring的生命周期中,BeanPostProcessor在初始化前后处理bean。 Spring中的bean每个都会经过Bean...

    Spring后置处理器BeanPostProcessor

    Spring提供了许多扩展点,如FactoryBean、Aware,这里还有BeanPostProcessor

    在Spring的生命周期中,BeanPostProcessor在初始化前后处理bean。

    在这里插入图片描述

    Spring中的bean每个都会经过Bean后置处理器,其中两个方法会一个一个接受bean的实例和beanName,判断类型进行处理即可。
    若想使用BeanPostProcessor对bean进行增强,实现该接口即可。
    还可以实现Ordered接口处理不同顺序的后置处理器。
    
    @Component
    public class BeanPost implements BeanPostProcessor {
        public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
            System.out.println(beanName);
            //通过类型处理
            if(bean instanceof User){
                //转换类型,赋值
                ((User) bean).setAge(19);
            }
            return bean;
        }
    
        public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
            System.out.println(bean);
            //通过名字处理
            if(beanName.equals("user")){
                ((User)bean).setSex("女");
            }
            return bean;
        }
    }
    
    
    User bean = ContextUtil.getBean(User.class);
    bean.setName("jack");//测试中只增加了姓名
    System.out.println(bean);
    
    
    //后置处理器中输出的内容
    user
    User(name=null, id=null, sex=null, age=19)
    
     //最后测试中输出的内容
    User(name=jack, id=null, sex=, age=19)
    
    展开全文
  • BeanPostProcessor:...参考博客:Spring后置处理器之-BeanPostProcessor BeanFactoryPostProcessor是什么:beanFactory的后置处理器; * 在BeanFactory标准初始化之后调用,来定制和修改BeanFactory的内容; * ...
  • 现了spring后置处理器beanpostprocessor。为什么说beanpostprocessor重要的呢?我们先来看看 他的作用。 BeanPostProcessor接口作用: 如果我们想在Spring容器中完成bean实例化、配置以及其他初始化方法前后要...
  • 最近在恶啃Spring源码,就读到一个很有意思的东西BeanPostProcessor,正式的名字叫做Spring后置处理器,这个东西非常的强大,强大到可以让我们干预Bean的创建过程,写出来分享给大家。更多Spring内容进入【Spring...
  • Spring中有一个接口BeanPostProcessor,该接口我们叫后置处理器,作用是在Bean对象实例化和依赖注入完毕后,在显示调用初始化方法的前后添加我们自己的逻辑。接口源码如下:一、自定义后置处理器/** * ...
  • Spring后置处理器详解

    千次阅读 2020-06-02 10:53:41
    spring-bean创建的生命周期与后置处理器的调用点 1.第一次调用BeanPostProcess , InstantiationAwareBeanPostProcessor中的postProcessBeforeInstantiation()方法. try { // Give BeanPostProcessors a chance to ...
  • Spring经过XML解析获取到了所有需要实例化Bean的信息并读取到BeanDefinition后,就保存在了...而beanFactory后置处理器,既BeanFactoryPostProcessor就是用来改变bean定义的。 invokeBeanFactoryPostProcessors
  • BeanPostProcessor也称为Bean后置处理器,它是Spring中定义的接口,在Spring容器的创建过程中(具体为Bean初始化前后)会回调BeanPostProcessor中定义的两个方法。 BeanPostProcessor的源码如下: public ...
  • 1.后置处理器BeanPostProcessor可以使bean在被创建之前和之后先运行一段代码 首先,实现一个继承了BeanPostProcessor的类,类中实现了postProcessBeforeInitialization和postProcessAfterInitialization两个方法 /* ...
  • 在前面几篇文章中梳理了Spring中bean的创建过程,在这个过程中各式各样的后置处理器发挥了不同的作用,可以说后置处理器贯穿了bean的实例化以及初始化过程。在这篇文章中,将按照出场顺序对后置处理器作用场景及发挥...
  • 后置处理器 两种后处理器 Bean后处理器,实现BeanPostProcessor接口 BeanFactory后处理器,实现BeanFactoryPostProcessor接口,也成为容器后处理器。 BeanPostProcessor简介: Bean后处理器用来对bean的功能进行扩展...
  • ApplicationListenerDetector:事件监听器的后置处理器

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 1,756
精华内容 702
关键字:

spring后置处理器

spring 订阅