Process of bean creation in spring [excerpt]

Source: Internet
Author: User
Tags i18n

1. The beans package provides the basic functions for managing and operating beans programmatically. The context package adds applicationcontext, which enhances the beanfactory function in a more framework-oriented manner.

2. The context package is based on the applicationcontext interface in the org. springframework. Context package. It is derived from the beanfactory interface and provides all the features of beanfactory. To work in a more framework-oriented way, the context package also provides the following functions to use the context of the hierarchy and inheritance relationship.

A. messagesource: Access to i18n messages.

B. resource access, such as URLs and files

C. The event is passed to the bean that absorbs the applicationlistener interface.

D. Load multiple (inherited) contexts so that each context focuses on a specific layer, such as the web layer of the application.

International support

1. applicationcontext extends the messagesource interface and provides messaging (i18n or international ). It can be used with nestingmessagesource to process classified information, which is the basic interface provided by spring to process information.

2. When an applicationcontext is loaded, it automatically finds the messagesource bean defined in the context. This bean must be handed in as messagesource. If such a bean is found, all calls to the above method will be delegated to the messagesource found. If messagesource is not found, applicationcontext will try to find out if his father contains a bean with the same name. If yes, it uses the bean as messagesource. If no information processing source is found, it creates a staticmessagesource.

3. Spring currently provides two messagesource implementations. They are

Resourcebundlemessagesource and staticmessagesource both enable nestingmessagesource to process nested information. Staticmessagesource is rarely used, but it provides a programming method to add information to the source. We often use resourcebundlemessagesource.

Use resources in spring

1. applicationcontext inherits the resourceloader interface. In this interface, the getresource () method is defined as follows:

Resource getresource (string location)

This method returns a resource handle. This handle should always be a reusable resource descriptor, allowing multiple calls to getinputstream ();

2. the parameter of the getresource () method is a resource access address, for example:

File: \ c:/test. Data

Classpath: Test. Data (find the test. dat file from the classpath path and return its resource handle)

A WEB-INF/test. dat

Note: The resource handle returned by the getresource () method does not mean that the resource actually exists. You need to call the exists () method of the resource interface to determine whether the resource exists.

Resource provides protocol-independent features.
Event Transfer

1. Time Processing in applicationcontext is provided through the appcationevent class and applicationlistener interface. If a bean implementing the applicationlistener interface is deployed in the context, the bean will be notified every time an applicationevent is published to applicationcontext. This is a standard observer design model.

2. Three standard events provided by spring

A. contextrefreshedevent

Events sent after applicationcontext is initialized or refreshed. Initialization means that all beans are loaded, Singleton is pre-instantiated, and applicationcontext is ready.

B. contextclosedevent

Events sent when the context is ended using the close () method of applicationcontext. This means that Singleton is destroyed.

C. requesthandledevent

A Web-related event tells all beans that an HTTP request has been responded (this time will be sent after a request ends -). Note: This time can only be applied to Web applications that use spring's dispatcherservlet.

==========================================

Lifecycle

1. initializingbean/init-Method

Implement the org. springframework. Beans. Factory. initializingbean interface to allow a bean to perform initialization after all its required attributes are set by beanfactory.

Of course, you can use init-method to replace this interface so that the application is not coupled with spring.

If a bean implements both initializingbean and init-method, spring first calls the initializingbean method and calls the method specified by init-method.

2. disposablebean/destroy-Method

Implement the org. springframework. Beans. Factory. disposablebean interface to allow a bean. You can get a callback when the beanfactory containing the bean is destroyed.

Note: beanfactory manages beans on a single instance by default. If the bean is not a single example, spring cannot manage its lifecycle.
3. beanfactoryaware

For classes that implement the org. springframework. Beans. Factory. beanfactoryaware interface, after being created by beanfactory, it will have a reference pointing to the created beanfactory.

4. beannameaware

If a bean implements Org. springframework. beans. factory. beannameaware interface is deployed to a beanfactory. beanfactory calls the bean through this interface to notify the bean of its deployed ID. This callback occurs after common bean property settings and before the initialization callback, such as the afterproperteis method (or custom init-method) of initializingbean ).

The bean lifecycle is as follows:

1. Bean Construction

2. Call the setxxx () method to set bean attributes.

3. Call beannameaware's setbeanname ();

4. Call beanfactoryaware's setbeanfactory () method

5. Call beanpostprocessor's postprocessbeforeinitialization () method

6. Call the afterpropertiesset () method of initializingbean.

7. Call the custom Initialization Method

8. Call the postprocessafterinitialization () method of the beanpostprocessor class

9. Call the destroy () method of disposablebean

10. Call the custom destruction method.

======================================

Extends the IOC framework of spring.

The IOC component of the Spring framework is designed to be scalable. Generally, application developers do not need to subclass the implementation classes of beanfactory or applicationcontext. By inserting specific access interfaces, Spring IoC containers can be expanded without restrictions.

Beanpostprocessor: called after Bean Creation

Beanfactorypostprocessors: called before bean Creation
1. If you want to execute custom logic before or after initializing a bean in the spring container, you can insert one or more beanpostprocessor instances.

2. The Org. springframework. Beans. Factory. config. beanpostprocessor Interface contains two callback methods. When a class is registered as the post-processor of the container, for each bean instance created by the container, the frontend and backend processors call any initialization method (such as afterproperties and the method declared using init-method) to obtain a callback from the container. The postprocessor can execute the desired action on the bean instance at will, or ignore the callback completely.

3. beanfactory and applicationcontext treat bean postprocessors slightly differently.

Applicationcontext automatically detects any bean provided to him that defines and implements the beanpostprocessor interface in the configuration metadata, registers them as a post-processor, and calls the bean when the container creates the bean. Deploying a postprocessor is no different from deploying other beans, and no other actions are required. On the other hand, when beanfactory is used, the bean postprocessor is eager to write the code that is displayed for registration.

4. the next extension point we see is:

Org. springframework. Beans. Factory. config. beanfactorypostprocessor. In addition to the main difference, the meaning of this interface is similar to beanpostprocessor. Beanfactorypostprocessor acts on bean definitions (for example, providing easy configuration metadata); that is, the Spring IoC container allows beanfactorypostprocessor to read configuration metadata and possibly modify it before it is easy to actually instantiate any bean.

5. Spring contains many existing Bean Factory postprocessors, such as propertyresourceconfigure, propertyplaceholderconfigure, and beannameautoproxycreator.

6. In a beanfactory, the application of beanfactorypostprocessor requires manual encoding. Applicationcontext detects the beans deployed on the beanfactorypostprocessor interface and automatically uses them as the backend processor for bean work when appropriate. Deploying a postprocessor is no different from deploying other beans, and no other actions are required.

7. propertyplaceholderconfigurer

As an implementation of a bean factory postprocessor, it can be used to place some attribute values in the beanfactory definition to another file in a separate Java properties format. This allows you to customize some key attributes (such as database URL, user name, and password) when deploying an application ), you do not need to make complex and dangerous changes to the main XML definition file or the file used by the container.

8. propertyoverrideconfigurer

Similar to propertyplaceholderconfigurer, but compared with the latter, the former can be interesting or has no value for bean attributes. If the properties file that overwrites the left and right does not have the content of a bean attribute, the context definition is used.

The definition of the bean factory is not covered by the conference room. Therefore, simply reading the XML definition file does not clearly know whether the overwriting configuration is effective. When multiple propertyoverridevers define different values for a bean attribute, the last one wins.

* ** It uses beanname. propertyname to specify the value, and does not need to be configured in bean.

9. register your custom propertyeditors

A. When bean attributes are set with string values, beanfactory actually uses the propertyeditor of the standard JavaBeans to convert these strings to complex types of attributes. Spring has registered a lot of customized propertyeditor in advance (for example, converting a string to my classname to a burst Class Object)

B. to compile an Attribute Editor, You can implement the propertyeditor interface by inheriting from the propertyeditorsupport class.

To use custom propertyeditors, you must use org. springframework. Beans. Factory. config. medmeditorconfigurer to register the custom property editor.

10. factorybean can be used as a proxy.

Org. springframework. Beans. Factory. factorybean

** To get factorybean itself, add &, that is, & beanname, before beanname.

* ******** Difference between beanfactory and applicationcontext *********

Applicationcontext creates all the beans during applicationcontext initialization and stores them in the cache.

Beanfactory creates a bean instance only when the bean needs to be obtained.

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.