Spring secrets Reading Notes 5 container startup

Source: Internet
Author: User

Spring secrets Reading Notes 5 container startup
The IoC container of Spring is used to produce beans and maintain the dependencies between beans. It loads Configuration Metadata (usually the Configuration information in XML format) in some way, and then binds the entire system object according to the information, finally, it is assembled into an available application system based on lightweight containers.
The IoC implementation process can be divided into two steps:

Startup phase analysis:
1. Add a resource file
2. Use BeanDefinitionReader to analyze resource files
3. Generate the corresponding BeanDefinition
4. Register BeanDefinition with BeanDefinitionRegistry.
Instantiation phase analysis:
Explicitly Calling container. getBean triggers bean instantiation.
When A is instantiated and A is dependent on B, the instantiation of B is triggered.


When instantiating an object, it first checks whether the object has been initialized. If not, it is initialized.
If there are dependent objects, inject them.
If the object implements some callback interfaces, it is equipped with the interface.


Spring for container startup provides a container extension mechanism called BeanFactoryPostProcessor. This mechanism allows us to modify the information stored in the BeanDefinition registered to the container before the container instantiates the corresponding object. This is equivalent to adding a process at the end of the first phase of container implementation. Let's perform some additional operations on the final BeanDefinition, such as modifying some attributes defined by bean, add other information for bean definitions.
BeanFactoryPostProcessor is used to implement this interface and write logic in the implementation class.
Let's first look at this interface

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;}
You can understand the above English. Allows for overriding or adding properties even to eager-initializing beans.
However, because Spring already provides several ready-made BeanFactoryPostProcessor implementation classes, we seldom implement a BeanFactoryPostProcessor on our own. Among them, org. springframework. beans. factory. config. PropertyPlaceholderConfigurer and org. springframework. beans. factory. config. Property overrideproceser are two commonly used BeanFactoryPostProcessor.


PropertyPlaceholderConfigurer generally, we do not want to mix system management-related information with Business Object-related configuration information into XML configuration files, this prevents errors during deployment or maintenance due to complicated XML configuration files. We will separately configure some database connection information, email server and other related information to a properties file. In this way, if the system resources change, you only need to pay attention to these simple properties configuration files.
Example:
Container uses BeanFactory
// Declare the BeanFactory instance that will be processed before using ablelistablebeanfactory beanFactory = new XmlBeanFactory (new ClassPathResource (...)); // declare the BeanFactoryPostProcessor PropertyPlaceholderConfigurer propertyPostProcessor = new PropertyPlaceholderConfigurer (); propertyPostProcessor. setLocation (new ClassPathResource (...)); // perform the post-processing operation propertyPostProcessor. postProcessBeanFactory (beanFactory );
Use Application
You only need to add
... 
    
      
       
           
     
      conf/myjdbc.properties
            
     
      conf/mail.properties
           
        
      
      ... 
   
After propertyPlaceHolderConfigure is used, the dataSource in xml is as follows:
    
      
   
    ${jdbc.url}
      
     
      
   
    ${jdbc.driver}
      
     
      
   
    ${jdbc.username}
      
     
      
   
    ${jdbc.password}
      
     
      
   
    true
      
     
      
   
    true
      
     ...
     

##myjdbc.properties jdbc.url=jdbc:mysql://server/MAIN?useUnicode=true&characterEncoding=ms932&failOverReadOnly=false&roundRobinLoadBalance=true jdbc.driver=com.mysql.jdbc.Driver jdbc.username=your username jdbc.password=your password 

 

$ {Jdbc. url} in xml corresponds to jdbc. url in properties.

There is nothing to say, it's just the dead content.


What PropertyOverrideConfigurerPropertyOverrideConfigurer does is to modify the information loaded from xml (whether or not it contains propertyPlaceHolderConfigure properties.
The following is the propeties file configuration information for PropertyOverrideConfigurer defined for dataSource:
# The file name is adjusment. properties dataSource. minEvictableIdleTimeMillis = 1000 dataSource. maxActive = 50
Note that this dataSource refers to beanName. ***
In this way, after the PropertyOverrideConfigurer is loaded to the container according to the following code, the dataSource is set
The default value is overwritten by the information in the pool-adjustment.properties file:
    
  
    < /bean> 
  
 
I will not go into details about PropertyOverrideConfigurer using BeanFactory.
To be honest, I don't think PropertyOverrideConfigurer is useful.


CustomEditorConfigurerjava is a strongly-typed language: int, String, String [], Person, and so on.
The xml we configured contains all the literal values. That is to say, all the raw data obtained by spring is strings.
So how does spring convert strings into various types?
What about tools?
What tools are used?
CustomEditorConfigurer
In Spring, properan PropertyEditor is used to convert the String type to other types. If you provide a PropertyEditor for each object type, you can obtain the corresponding PropertyEditor Based on the object type for specific type conversion. Spring containers use the default PropertyEditor search logic in the JavaBean framework when performing type conversion.
At the same time, the Spring framework also provides some Property-Editor implemented by itself.
StringArrayPropertyEditor. This PropertyEditor converts a String in CSV format into a String [] array. By default, it is a String separated by commas (,), but can be specified to separate custom strings.
. ByteArrayPropertyEditor and CharArrayPropertyEditor all belong to the Property-Editor with similar functions. You can obtain detailed information by referring to Javadoc.
ClassEditor. Converts a class Name of the String type to a corresponding Class object, which is equivalent to the function of using Class. forName (String. You can use the String [] array to input the value to be converted to achieve the same purpose as the ClassArrayEditor provided.
FileEditor. Spring provides PropertyEditor corresponding to the java. io. File type. PropertyEditor, InputStreamEditor, and URLEditor, which are used to locate resources.
LocaleEditor. For java. util. Locale-type PropertyEditor, you can refer to the Javadoc instructions of Local-eEditor and Locale.
PatternEditor. For the Property-Editor of java. util. regex. Pattern introduced after JavaSE1.4, the format can be referred to Javadoc of java. util. regex. Pattern class.
More information about CustomEditorConfigurer reference http://blog.csdn.net/zhoudaxia/article/details/36247883#t4


Note:
According to the specifications of the JavaBeans, the infrastructure of the JavaBeans will find the existence under the same class package of the JavaBean. Editor class. It is automatically used if it exists. As the PropertyEditor of the JavaBean.
For example, com. baobaotao. domain. UserEditor automatically becomes the PropertyEditor corresponding to com. baobaotao. domain. User. Spring also supports this specification, that is, if you use this specification command PropertyEditor, you do not need to explicitly register it in CustomEditorConfigurer. Spring will automatically find and register this PropertyEditor. (You don't even need to use the bean label in xml to declare a UserEditor)



If the implementation of BeanFactory is used, such as XmlBeanFactory, The CustomEditorConfigurer can be applied to the container in a well-coded manner.

XmlBeanFactory beanFactory = new XmlBeanFactory (new ClassPathResourceCustomEditorConfigurer ceConfigurer = new medmeditorconfigurer (); Map customerEditors = new HashMap (); customerEditors. put (java. util. date. class, new DatePropertyEditor (); // any string to Date type will use DatePropertyEditorceConfigurer. setCustomEditors (customerEditors); ceConfigurer. postProcessBeanFactory (beanFactory );

DatePropertyEditor is as follows:

If we want to convert a string of a certain format to the Person class, we can use the above method, but if we want to convert spring to date, we cannot create a new package named java. util.
So we need to let the container know the implementation of CustomEditorConfigurer.

The hard encoding method is used.

If ApplicationContext is used, xml is as follows:

Use Time:

Note that what I pass to DateFoo is a string in the datePattern format of DatePropertyEdit, which is a parameter in the setAsTest method of DatePropertyEdit.

Through CustomerEditorConifgure, Spring has learned that anyone who wants to convert String to Date should be able to understand datePropertyEdit...

However, spring2.0 and later are recommended to use the propertyEditorRegistrars attribute to specify the custom PropertyEditor. In this way, we will take another step to implement the PropertyEditorRegistrar interface.


Then register in xml as follows:

 

Related Article

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.