[Original] Spring 2.0 Technical Manual Study Notes-Chapter 3 bean, messages, events

Source: Internet
Author: User

3.1 bean basic management

1. The beanfactory interface defines the object getbean (string, class) method, and obtains the corresponding bean instance by specifying the name set in the bean definition file,And convert to the specified class.

 

2. applicationcontext can read multiple bean definition files through arrays, such:

 
Applicationcontext context = new classpathxmlapplicationcontext (New String [] {"beans-config.xml", "beans-config2.xml "});

 

You can also specify the * character. The following example reads all xml configuration files starting with "beans" in classpath. Note that this method is only useful in the actual file system. If it is in the. jar file, the following settings are invalid:

Applicationcontext context = new classpathxmlapplicationcontext ("Beans *. xml ");

 

 

3. When multiple bean definition files are required, you can use the <import> label, for example:

 
<Beans> <import resource = "dao-config.xml"> <bean id = "bean1" class = "... "> <bean id =" bean2 "class = "... "> </beans>

 

<Import> the tag must be placed before the <bean> tag, and the definition file must be placed in the same directory or classpath to specify the location of the bean definition file in the relative path.

 

4. There are two methods to specify the bean alias. One is to use the <alias> label, for example:

 
<Beans> <bean id = "datasource" class = "... "> <alias name =" datasource "alias =" device: datasource "> <alias name =" datasource "alias =" User: datasource ">... </beans>

 

Another method is to use the name attribute of the <bean> label to directly specify multiple aliases separated by commas, for example:

 
<Beans...> <bean id = "datasource" name = "device: datasource, user: datasource" class = "..."> </beans>

 

5. Use static factory method and factory bean to instantiate Bean

Bean can be instantiated through the static factory method. Assume that the following interface is used:

 
Public interface imusicbox {public void play ();}

Create the musicboxfactory class and obtain the imusicbox instance. The static method creatmusicbox () is responsible:

 
Public class musicboxfactory {public static imusicbox createmusicbox () {return New imusicbox () {public void play () {system. out. println ("playing piano music ");}};}}

Bean configuration is as follows. Note that the class attribute value of musicbox is not its own class. It must be the factory class (musicboxfactory in this example) that can obtain the class ).

<Bean id = "musicbox" class = "Spring. chapter3.musicboxfactory" factory-method = "createmusicbox"/>

In addition, the factory method can be non-static. For example, the creatmusicbox () method in the previous example can also be an instance method. To create an instance bean, you must first obtain the bean of the factory class, the specific configuration is as follows:

 
<Bean id = "musicboxfactorybean" class = "Spring. chapter3.musicboxfactory"/> <bean id = "musicbox" factory-bean = "musicboxfactorybean" factory-method = "createmusicbox"/>

Note: factory-bean specifies an instance of the factory class. Spring will use the instance specified by factory-bean to call the method specified by factory-method to obtain an instance bean.

 

6. Bean Lifecycle

If beanfactory is used to generate and manage beans, the following declaration periods are supported as much as possible:

• Bean Creation

Beanfactory reads the bean definition file and generates various bean instances.

• Property Injection

Execute bean property dependency injection.

• Beannameaware setbeanname ()

If the Bean class implements the org. springframework. Beans. Factory. beannameaware interface, execute its setbeanname () method.

• Beanfactoryaware's setbeanfactory ()

If the Bean class implements the org. springframework. Beans. Factory. beanfactoryaware interface, execute its setbeanfactory () method.

• Postprocessbeforeinitialization () of beanpostprocessors ()

If any org. springframework. Beans. Factory. config. beanpostprocessors instance is associated with the bean instance, The postprocessbeforeinitialization () method of the beanpostprocessors instance is executed.

• Afterpropertiesset () of initializingbean ()

If the Bean class implements org. springframework. Beans. Factory. initializingbean, execute its afterpropertiesset () method.

• Define init-method in the bean definition file

You can use the init-method attribute in the bean definition file to set the method name. If this attribute is setCodeAt this stage, the method specified by the init-method attribute is executed.

• Postprocessafterinitialization () of beanpostprocessors ()

If any beanpostprocessors instance is associated with the bean instance, The postprocessafterinitialization () method of the beanpostprocessors instance is executed.

• Destroy () of disposablebean ()

When the container is closed, if the Bean class implements the org. springframework. Beans. Factory. disposablebean interface, execute its destroy () method.

• Destroy-method defined in the bean definition file

When the container is closed, you can use the destroy-method attribute in the bean definition file to set the method name. If this attribute is set, when the code runs to this stage, the method specified by the destroy-method attribute is executed.

 

If all beans have the same initialization method name and destruction method name, such as Init () and destroy (), you can define the default-init-method and default-destroy-method attributes on <beans>, so that spring will automatically execute the init () method and destroy () method of each bean.

 

7. If beanfactory is used, the bean will be instantiated only when the getbean () method is used to actually obtain the bean. If applicationcontext is used, all beans are instantiated according to the bean definition file in advance. In this mode, you can set the lazy-init attribute to true on <bean> so that the applicationcontext will not instantiate the bean when it is started again.

 

 

8. Bean inheritance

In the bean definition file, a bean can inherit the configurations of another bean, as long as the parent attribute is set to the ID of the bean to be inherited during the bean definition. The abstract attribute of the inherited bean can be set to true, so that the bean cannot be instantiated and can only be inherited as the parent bean of other beans. This is similar to the abstract class in Java. In addition, beans whose abstract attribute is true do not need to specify the class attribute.

 

9. lookup method Injection

Lookup method injection is mainly used to obtain non-singleton bean through the lookup-method when non-singleton bean is used in the singleton object. Let's look at the example below.

 
<Bean id = "sysmessage" class = "test. Message" Scope = "prototype">

A common bean, sysmessage, is created here. The related class code is as follows:

Pakage test; import Java. util. date; public class message {private string sysmessage; public message () {sysmessage = "now date:" + new date (). tostring () ;}public string tostring () {return sysmessage ;}}

The function of the message object is to obtain the date of the system.

Now, a messagemanager class is designed. When the display () method is called, a message object is created and displayed. Note that this is an abstract class and contains the abstract method createmessage ():

 
Package test; public class messagemanager {public void display () {message = createmessage (); system. Out. println (Message);} protected abstract message createmessage ();}

The configuration information is as follows:

 
<Bean id = "messagemanager" class = "test. messagemanager"> <lookup-method name = "createmessage" bean = "sysmessage"/> </bean>

The name attribute of the lookup-method element specifies an abstract method, and the bean attribute specifies the bean to be passed in. Each time you call a method specified by the name attribute, a bean specified by the bean attribute is passed in. In this way, although messagemanager has been created at the beginning of container creation, every time the display method is executed, a new message object is obtained to obtain the new system date information.

If you use the traditional method, add a message type member attribute in the messagemanager class and inject it through spring. The date obtained each time the display () method is called is the same value, even if the scope of the message object is specified as prototype. Because the messagemanager object was created when the container was created, a fixed message object has been coupled. Every time the display () method is called, a new message object will not be obtained.

 

10. beanpostprocessor Interface

IfAn Implementation classIf a container is registeredEach managed BeanA callback of the implementation class of this interface is obtained before the initialization method is called. When the container calls the method defined by the interface, the instance and name of the managed bean are passed in to the method through parameters. After processing, the return value of the method is returned to the container.

NOTE: If we use multiple beanpostprocessor implementation classes, how can we determine the processing sequence? In fact, you only need to implement the ordered interface and set the order attribute to easily determine the processing sequence of different implementation classes.

Beanfactory and applicationcontext treat bean postprocessors slightly differently. Applicationcontext automatically detects all beans that implement the beanpostprocessor interface in the configuration file, registers them as a postprocessor, and calls the bean when the container creates the bean. Deploying a postprocessor is no different from deploying other beans. When beanfactory is used, the bean postprocessor must explicitly register with the following code:

Resource resource = new filesystemresource ("applicationcontext. XML "); configurablebeanfactory factory = new xmlbeanfactory (Resource); // instantiate a beanpostprocesser interface implementation class beanpostprocessorimpl instance beanpostprocessorimpl beanpostprocessor = new pipeline (); // For beanfactory, beanpostprocessorfactory must be registered explicitly. addbeanpostprocessor (beanpostprocessor );

 

11. parse text messages

Applicationcontext inherits the org. spriingframework. Context. Support. messagesource interfaces. You can use the getmessage () method to obtain the resource file of text messages, so that messages can be internationalized and localized.

You can simply use the messagesource implementation org. springframework. Context. Support. resourcebundlemessagesource to obtain international messages. Note that you must configure a bean of this class in the bean configuration file and set its basename attribute. The attribute value is the basename of the resource file. For example:

 
<Bean id = "messagesource" class = "org. springframework. Context. Support. resourcebundlemessagesource"> <property name = "basename" value = "messages"/> </bean>

The preceding configuration indicates that the resource file starts with messages, for example, messages_zh_cn.properties or messages_en_us.properties. With the above configuration, you can easily use the getmessage () method to obtain international messages:

Applicationcontext context = new classpathxmlapplicationcontext ("applicationcontext. XML "); object [] arguments = {" Jack ", calendar. getinstance (). gettime ()}; system. out. println (context. getmessage ("hello", arguments, locale. US); system. out. println (context. getmessage ("hello", arguments, locale. PRC ));

The getmessage () method has three parameters. The first parameter specifies the resource file (messages _*_*. the key name of the key-Value Pair in properties. The second parameter is an array of the object type, indicating that if the message content contains runtime parameters such as {0}, {1} (for example: hello = Hello, {0 }!), You can use this array to pass in related parameters. The third parameter is the locale type to be displayed. If locale. PRC is specified, the Chinese version of the message needs to be displayed.

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.