Spring strategy learning notes (2.11) -- post-bean Processor

Source: Internet
Author: User

I. knowledge points

The bean post-processor allows additional bean processing before and after the initialization callback method. The main feature of the bean postprocessor is to process all bean instances in the IOC container one by one, not just a single bean instance. In general, the bean postprocessor is used to check the validity of bean attributes or modify bean attributes according to specific conditions.

The basic requirement of bean post-processor is to implement the beanpostprocessor interface. By implementing the postprocessbeforeinitialization () and postprocessafterinitialization () methods, you can process all beans before and after the callback method is initialized. Spring will pass each bean instance to the two methods before and after calling the initialization callback method. The steps are as follows:

(1) create a bean instance using constructors or factory methods

(2) set values for bean properties and bean reference

(3) Call the value setting method defined in the sensing interface

(4) Pass the bean instance to the postprocessbeforeinitialization () method in each bean post-Processor

(5) Call the initialization callback Method

(6) Pass the bean instance to the postprocessor postprocessafterinitialization () method of each bean.

(7) bean is ready for use

(8) Call the destroy callback function when the container is closed.

When the Bean Factory is used as an IOC container, the bean post-processor can only register by programming, that is, register by using the addbeanpostprocessor method. If you use the application context, you only need to declare a processor instance in the bean configuration file, and it will automatically register.

Ii. Sample Code

Storageconfig tag Interface

Package COM. codeproject. jackie. springrecipesnote. springadvancedioc;/*** mark the interface to differentiate the bean backend processor from the bean to be checked * @ author Jackie **/public interface storageconfig {Public String getpath ();}

Cashier class

Package COM. codeproject. jackie. springrecipesnote. springadvancedioc; import Java. io. bufferedwriter; import Java. io. file; import Java. io. filewriter; import Java. io. ioexception; import Java. util. date; import Org. springframework. beans. factory. beannameaware;/*** cashier class implements beannameaware aware interfaces and storageconfig flag interfaces * @ author Jackie **/public class cashier implements beannameaware, storageconfig {private string name; private bufferedwriter writer; private string path; Public void setpath (string path) {This. path = path;} public void openfile () throws ioexception {file = new file (path, name + ". TXT "); filewriter fw = new filewriter (file, true); writer = new bufferedwriter (FW);} public void checkout (shoppingcart cart) throws ioexception {double Total = 0; for (product: cart. getitems () {total + = product. getprice ();} writer. write (new date () + "\ t" + total + "\ r \ n"); writer. flush ();} public void closefile () throws ioexception {writer. close () ;}@ overridepublic string getpath () {return path ;}@ overridepublic void setbeanname (string beanname) {This. name = beanname ;}}

Pathcheckingbeanpostprocessor custom bean post-Processor

Package COM. codeproject. jackie. springrecipesnote. springadvancedioc; import Java. io. file; import Org. springframework. beans. beansexception; import Org. springframework. beans. factory. config. beanpostprocessor;/*** common component, before opening the file, make sure that the * @ author Jackie **/public class pathcheckingbeanpostprocessor implements beanpostprocessor {/*** check the path before opening the file. * an instance of the bean to be processed must be returned. * // @ Overridepublic object postprocessbeforeinitialization (Object bean, string beanname) throws beansexception {// If the bean implements the storageconfig interface, check whether the path exists if (bean instanceof storageconfig) {string Path = (storageconfig) bean ). getpath (); file = new file (PATH); If (! File. exists () {file. mkdirs () ;}} return bean;}/*** the original bean instance */@ overridepublic object postprocessafterinitialization (Object bean, string beanname) must be returned even if nothing is done) throws beansexception {return bean ;}}

Bean Configuration

<? 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-3.2.xsd"> <! -- Register the bean post-Processor --> <Bean class = "com. codeproject. jackie. springrecipesnote. springadvancedioc. pathcheckingbeanpostprocessor "/> <bean id =" AAA "class =" com. codeproject. jackie. springrecipesnote. springadvancedioc. battery "> <property name =" name "value =" AAA "/> <property name =" price "value =" 2.5 "/> </bean> <bean id =" cdrw "class =" com. codeproject. jackie. springrecipesnote. springadvancedioc. battery "> <property name =" name "value =" CD-RW "/> <property name =" price "value =" 1.5 "/> </bean> <bean id =" dvdrw "class =" com. codeproject. jackie. springrecipesnote. springadvancedioc. battery "> <property name =" name "value =" DVD-RW "/> <property name =" price "value =" 3.0 "/> </bean> <bean id =" shoppingcart "class =" com. codeproject. jackie. springrecipesnote. springadvancedioc. shoppingcart "Scope =" prototype "/> <bean id =" cashier1 "class =" com. codeproject. jackie. springrecipesnote. springadvancedioc. cashier "init-method =" openfile "Destroy-method =" closefile "> <property name =" path "value =" C: /cashier1 "/> </bean> </beans>

Test class

package com.codeproject.jackie.springrecipesnote.springadvancedioc;import java.io.IOException;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;/** * @author jackie * */public class BeanPostProcessorTest {@Testpublic void testBeanPostProcessor() throws IOException {ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");Product aaa = (Product) applicationContext.getBean("aaa");Product cdrw = (Product) applicationContext.getBean("cdrw");Product dvdrw = (Product) applicationContext.getBean("dvdrw");ShoppingCart shoppingCart = (ShoppingCart) applicationContext.getBean("shoppingCart");shoppingCart.addItem(aaa);shoppingCart.addItem(cdrw);shoppingCart.addItem(dvdrw);    Cashier cashier = (Cashier) applicationContext.getBean("cashier1");    cashier.checkout(shoppingCart);}}

Note: The book says that if you use the JSR-250 annotation @ postconstruct and @ predestroy, and a commonannotationbeanpostprocessor instance calls the initialization method, then pathcheckingbeanpostprocessor does not work properly because its default priority is lower than commonannotationbeanpost. My practice has proved that pathcheckingbeanpostprocessor can still work normally.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.