Spring in the post-processor to explain BeanPostProcessor

BeanPostProcessor interface role:

     If we want to finish bean instantiated, configured in the Spring container and other initialization methods before and want to add some of your own logic. We need to define one or more classes BeanPostProcessor interface, and then to register Spring IoC container.

package com.test.spring;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
/**
 * bean后置处理器
 * @author zss
 *
 */
public class PostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean,
            String beanName) throws BeansException {
        if ("narCodeService".equals(beanName)) {//过滤掉bean实例ID为narCodeService
            return bean;
        }
        System.out.println("后置处理器处理bean=【"+beanName+"】开始");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean,
            String beanName) throws BeansException {
        if ("narCodeService".equals(beanName)) {
            return bean;
        }
        System.out.println("Post processor bean = [" + beanName + "] is completed!" );
         The try { 
            the Thread.sleep ( 1000 ); 
        } the catch (InterruptedException E) { 
            e.printStackTrace (); 
        } 
        return the bean; 
    } 

}

Note: two interface methods can not return null, null is returned if it will be reported in a subsequent initialization method or by the getBean null pointer exception () method to get an object not bena instance, because the postprocessor removed from the bean instance Spring IoC container the object is not put back again IoC container!

The postprocessor Spring PostProcessor Spring configuration file to configure

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- 定义一个bean -->
     <bean id="narCodeService" class="com.test.service.impl.NarCodeServiceImpl">
     </bean>
    <bean id="beanLifecycle" class="com.test.spring.BeanLifecycle" init-method="init" destroy-method="close">
        <property name="name" value="张三"></property>
        <property name="sex" value="男"></property>
    </bean>

    <!-- Spring后置处理器 -->
    <bean id="postProcessor" class="com.test.spring.PostProcessor"/>
</beans>

BeanPostProcessor API:

public  interface the BeanPostProcessor {   
  
    // instantiate dependency injection is completed, the completion of some custom initialization tasks before initialization call display   
    Object postProcessBeforeInitialization (Object the bean, the beanName String) throws BeansException;   
  
     
    // instantiate dependency injection is performed when initialized   
    Object postProcessAfterInitialization (Object the bean, the beanName String) throws BeansException;   
  
}
Can be seen from the API: 
. 1: Method postProcessorBeforeInitailization postprocessor is instantiated bean, and custom dependency injection after initialization methods (e.g.: Add bean tag profile init-method attribute specifies the Java class initialization method,
@ PostConstruct annotation designated initializer, Java classes implement InitailztingBean interface) before the call
2: postProcessorAfterInitailization method postprocessor bean is instantiated, dependency injection and customizing initialization method calls

Note:
1.BeanFactory ApplicationContext and two bean containers treated the post processor is slightly different. Spring ApplicationContext container configuration file will automatically detect those corresponding to the Java class implements bean BeanPostProcessor
interface and automatically register them as post-processors. Creation bean call them in the process, so the deployment of a post-processor does not have much difference with the ordinary bean.

      Must register the code displayed when 2.BeanFactory containers registration bean post-processors, ConfigurableBeanFactory IoC container interface inheritance hierarchy defined in a registration method

   void addBeanPostProcessor(BeanPostProcessor beanPostProcessor);

 Spring how to call multiple BeanPostProcessor implementation class:

    We can add a plurality of the BeanPostProcessor Spring configuration file (post processor) interface class, Spring container will in turn call according to the order defined postprocessor default.

Spring configuration file:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!-- bean定义 -->    
    <bean id="narCodeService" class="com.test.service.impl.NarCodeServiceImpl">
    </bean>
    <bean id="postProcessor" class="com.test.spring.PostProcessor"/>
    <bean id="postProcessorB" class="com.test.spring.PostProcessorB"/>
</beans>

BeanPostProcessor implementation class:

package com.test.spring;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
/**
 * bean后置处理器
 * @author zss
 *
 */
public class PostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean,
            String beanName) throws BeansException {
        System.out.println("后置处理器处理bean=【"+beanName+"】开始");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean,
            String beanName) throws BeansException {
        System.out.println("后置处理器处理bean=【"+beanName+"】完毕!");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return bean;
    }
}
----------------------------------------------------------------------------------------------------------------------------------------
package com.test.spring;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

public class PostProcessorB implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean,
            String beanName) throws BeansException {
        System.out.println("后置处理器开始调用了");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean,
            String beanName) throws BeansException {
        System.out.println("后置处理器调用结束了");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return bean;
    }
}

Test case:

package com.test.spring;

import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class T {
    AbstractApplicationContext applicationcontext=null;
    @Before
    public void before() {
        System.out.println("》》》Spring ApplicationContext容器开始初始化了......");
        applicationcontext= new ClassPathXmlApplicationContext(newString [] { "test1-service.xml" }); 
        System.out.println ( "" "" the Spring of the ApplicationContext container initialized ...... " ); 
    } 
    @Test 
    public  void   Test () { 
        ApplicationContext. the registerShutdownHook ();    
    } 
}

Test Results:

"" "Spring ApplicationContext container starts to initialize a ......
 2017-03-19 10:50:29 INFO: ClassPathXmlApplicationContext-Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@18c92ff9: the Startup DATE [Sun Mar 19 10: CST 2017 50:29]; the root of context Hierarchy
 2017-03-19 10:50:29 the INFO: Loading the XML-XmlBeanDefinitionReader from the bean class path Resource Definitions [test1- service.xml] 
postprocessor process the bean = [] narCodeService start 
postprocessor start calling the 
post-processor bean = [] narCodeService finished! 
postprocessor call ended 
"" "Spring ApplicationContext container initialization finished ......
2017-03-19 10:50:34  INFO:ClassPathXmlApplicationContext-Closing org.springframework.context.support.ClassPathXmlApplicationContext@18c92ff9: startup date [Sun Mar 19 10:50:29 CST 2017]; root of context hierarchy

It can be specified in the call sequence postprocessor Spring mechanism by BeanPostProcessor interface so the Ordered interface getOrder class implements a method, which returns an integer, the default value is 0, the highest priority, the lower the priority value

Guess you like

Origin www.cnblogs.com/deityjian/p/11306353.html