(Spring-9th back [IoC Basics]) BeanFactoryPostProcessor, the second best tool before Bean instantiation, beanfactory. getbean

Source: Internet
Author: User
Tags log log

(Spring-9th back [IoC Basics]) BeanFactoryPostProcessor, the second best tool before Bean instantiation, beanfactory. getbean

The inheritance structure is shown above. BeanFactoryPostProcessor is used when loading XML, registering bean definition, and before instantiating bean definition. It restores some placeholder attributes in XML into real values. This means that, sometimes, the <bean> attribute value in XML is not fixed and will change with external factors. At this time, the placeholder is configured in <bean>, define an attribute file to control the <bean> attributes. For example, the following is an XML configuration for database connection:

1 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"2         destroy-method="close" 3         p:driverClassName="${driverClassName}" 4         p:url="${url}"5         p:username="${userName}" 6         p:password="${password}" />

A jdbc. properties is defined below:

1 dbName=sampledb2 driverClassName=com.mysql.jdbc.Driver3 url=jdbc:mysql://localhost:3306/${dbName}4 #userName=root5 #password=1234

Read the property value from jdbc. properties and assign it to a placeholder similar to $ {password} in <bean> xml. The BeanFactoryPostProcessor implementation class is required. In this example, we can use PropertyPlaceHolderConfigurer.

Example:

First, there are four files in total:

Car. java: the simplest bean class. The source code is as follows:

1 public class Car {2 private String name; 3 private String color; 4 private double price; 5 6 private Log log = LogFactory. getLog (Car. class); 7 8 public Car () {9 // name = "BMW"; 10 log.info ("calls the Car constructor and instantiates the Car .. "); 11} 12 13 14 public String getName () {15... 16...

The getter and setter methods are omitted later.

Main. java, simple startup class, as follows:

 1 public class Main { 2     private static Log log=LogFactory.getLog(Main.class); 3      4     public static void main(String args[]){ 5         ApplicationContext ctx = new ClassPathXmlApplicationContext("com/mesopotamia/test2/*.xml"); 6         Car car = ctx.getBean("car",Car.class); 7         log.info(car.toString()); 8     } 9 10 }

The property file of car. properties and car:

1 name = Audi A62 color = yellow 3 price = 50.00

 

Beans. xml, configuration file. The details are not the same as those described in the previous articles:

 1 <?xml version="1.0" encoding="UTF-8" ?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" 4     xmlns:context="http://www.springframework.org/schema/context" 5     xsi:schemaLocation="http://www.springframework.org/schema/beans  6          http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 7          http://www.springframework.org/schema/context 8          http://www.springframework.org/schema/context/spring-context-3.0.xsd">       9        <context:property-placeholder10          location="classpath:com/mesopotamia/test2/car.properties"11          file-encoding="utf8"12         />13     <bean id="utf8" class="java.lang.String">14         <constructor-arg value="utf-8"></constructor-arg>15     </bean> 16     <bean id="car" class="com.mesopotamia.test2.Car"17         p:name="${name}" 18         p:color="${color}"19         p:price="${price}"/>20 </beans>

The running result is as follows:

1 22:08:59, 155 INFO [main] (Car. java: 15)-the Car constructor is called and the Car is instantiated .. 2 22:08:59, 167 INFO [main] (Main. java: 15)-Name: AUDI A6 color: yellow; Price: 50.0

In beans. xml,

The context and p rules are used.

<Context: property-placeholder two attributes: Find the property file, and set the corresponding encoding method (the default is ISO-8559-1, loading Chinese will garbled, so transcoding)

After you configure the transcoding attribute, you need to write a bean with a encoding format of 13-15 lines (this is a little cool ).

The placeholder is like 17 rows: $ {...}.

After this configuration, spring will automatically search for classpath: com/mesopotamia/test2/car. properties is encoded in UTF-8 format and assigned to the corresponding attribute of bean definition whose id is car.

By default, spring automatically starts the post-processor of the PropertyPlaceHolderConfigurer factory.

 

We have not manually registered PropertyPlaceHolderConfigurer. How does spring load PropertyPlaceHolderConfigurer Based on context: property-placeholder?

 

Answer: I have talked about spring-handlers and spring-schemas files in the META-INF folder, spring-handlers can find specific processing classes according to the namespace, the following is the spring-handlers file of the context rule:

1 http\://www.springframework.org/schema/context=org.springframework.context.config.ContextNamespaceHandler2 3 http\://www.springframework.org/schema/jee=org.springframework.ejb.config.JeeNamespaceHandler4 http5 6 \://www.springframework.org/schema/lang=org.springframework.scripting.config.LangNamespaceHandler7 http8 9 \://www.springframework.org/schema/task=org.springframework.scheduling.config.TaskNamespaceHandler

The first line tells us that the corresponding processing class of the context rule is org. springframework. context. config. ContextNamespaceHandler. Now we enter this class:

 1 public class ContextNamespaceHandler extends NamespaceHandlerSupport { 2  3     public void init() { 4         registerBeanDefinitionParser("property-placeholder", new PropertyPlaceholderBeanDefinitionParser()); 5         registerBeanDefinitionParser("property-override", new PropertyOverrideBeanDefinitionParser()); 6         registerBeanDefinitionParser("annotation-config", new AnnotationConfigBeanDefinitionParser()); 7         registerBeanDefinitionParser("component-scan", new ComponentScanBeanDefinitionParser()); 8         registerBeanDefinitionParser("load-time-weaver", new LoadTimeWeaverBeanDefinitionParser()); 9         registerBeanDefinitionParser("spring-configured", new SpringConfiguredBeanDefinitionParser());10         registerBeanDefinitionParser("mbean-export", new MBeanExportBeanDefinitionParser());11         registerBeanDefinitionParser("mbean-server", new MBeanServerBeanDefinitionParser());12     }13 14 }

The fourth line shows at a glance that spring sees property-placeholder, and a new PropertyPlaceholderBeanDefinitionParser object is created. This object has a method:

1 @Override2     protected Class getBeanClass(Element element) {3         return PropertyPlaceholderConfigurer.class;4     }

This makes it clear. In fact, the attributes under <context: property-placeholder are the attributes under PropertyPlaceholderConfigurer. Below are several important attributes:

Locations: location is enough for an attribute file, while multiple attribute files are locations, which are inherited from:

PropertiesLoaderSupport (parent class of the parent class of PropertyPlaceholderConfigurer ). Type: Properties [].

FileEncoding: encoding format. It is also the property of PropertiesLoaderSupport.

Order: If the configuration file defines multiple propertyplaceholdertransferer, order specifies the execution order. This property is inherited from PropertyResourceConfigurer.

PlaceholderPrefix: for example, "$ {" is the placeholder header. It can also be defined as another placeholder header. For example, if you write & {...} &, placeholderPrefix must be defined &&{.

PlaceholderSuffix: placeholder tail character. These two attributes belong to PropertyPlaceholderConfigurer.

 

Generally, attributes are not assigned a value before instantiating a Bean, even if they are not assigned a value during instantiation. This is equivalent to a new object. However, if the attribute value of <bean> is defined in the configuration file, the attribute value is loaded after XML is loaded and BeanDefinition is formed before instantiation. This is not the instantiation process, it is not the process of defining attribute values when bean objects are used.

 

 

The determination is not strong, and the end is not good.

------ <Song> Zhu Xi

 

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.