Today we learned about Spring's beanpostprocessor interface, which is: if we need to add some of our own logic processing to the spring container after the bean instantiation, configuration and other initialization, We can define the implementation of one or more beanpostprocessor interfaces.
Let's look at a simple example
PackageCom.spring.test.di;Importorg.springframework.beans.BeansException;ImportOrg.springframework.beans.factory.config.BeanPostProcessor; Public classBeanpostprcessorimplImplementsBeanpostprocessor {//processing before a Bean is instantiated PublicObject Postprocessbeforeinitialization (Object bean, String beanname)throwsbeansexception {System.out.println ("Object" + Beanname + "Start instantiation"); returnBean; } //processing after a Bean is instantiated PublicObject Postprocessafterinitialization (Object bean, String beanname)throwsbeansexception {System.out.println ("Object" + Beanname + "instantiation Complete"); returnBean; }}
As long as the implementation of this beanpostprocessor interface is defined in the container, as follows:
<class= "Com.spring.test.di.BeanPostPrcessorImpl"/>
The test code is as follows:
PackageCom.spring.test.di;ImportOrg.springframework.context.ApplicationContext;ImportOrg.springframework.context.support.FileSystemXmlApplicationContext; Public classTestmain {/** * @paramargs*/ Public Static voidMain (string[] args)throwsException {//Get ApplicationContext ObjectApplicationContext CTX=NewFilesystemxmlapplicationcontext ("Applicationcontext.xml"); //Get BeanCtx.getbean ("Logic"); }}
Running the above test program, you can see the results of the console printing:
Object logic begins to instantiate
Object Logic Instantiation Complete
The scope of the Beanpostprocessor is container-level, which is related only to the container in which it resides. If you define beanpostprocessor in a container, it simply resets the beans in this container. It does not do any processing on beans that are defined in another container.
Note the point:
beanfactory applicationcontext treat bean a slightly different post processor. ApplicationContext automatically detects beanpostprocessor in the configuration file all the beans on the interface, register them as a post processor, and then call it when the container creates the bean at the appropriate time. Deploying a post processor is no different from deploying other beans. Instead of using beanfactory Implementation, the Bean post processor must be explicitly registered with a code similar to the following:
New New Filesystemresource ("Applicationcontext.xml"new Xmlbeanfactory (Resource); Factory.addbeanpostprocessor (Beanpostprocessor); Factory.getbean ("logic");
Spring's Beanpostprocessor interface implementation