Spring Study Notes: bean Configuration

Source: Internet
Author: User
Tags date now

Retrieving a bean from the Spring IoC container is very easy. As you can see earlier, context. getbean ("bean name ");
The key is to configure the bean. We configured a bean named mybook;
<Bean id = "mybook" class = "model. book "> <br/> <property name =" ID "value =" 000002 "/> <br/> <property name =" name "value =" thinking in Java "/> <br/> <property name = "author" value = "Bruce Eckel"/> <br/> <property name = "price" value = "2222"/> <br /> </bean> 
When assembling this bean, the IOC container first calls the book's default constructor book () to create a book object, and then calls the set methods of book through reflection to assign values to the attributes of book, finally, the bean will be cached and waiting for use.
Now let's talk about Bean configuration.
The simplest scenario:
<Bean id = "DT" class = "Java. util. Date"> </bean>

In this case, the default constructor of date is called to obtain the runtime time.
Property injection:Just like the previous mybook,Two points to be pointed out are::
1. the property to be injected must have the setter method. 2. There must be a default constructor. The reason is that when the IOC container assembles the bean, first, call the default constructor to create an object, and then call each set method through reflection to assign values to the attribute. for example, in the previous book class, if you add a constructor, such:
Public book (string ID, string name, string author, float price)
Add a default constructor public book () {} at the same time, because if you do not provide a constructor in the Java language specification, the JVM automatically adds a default constructor, however, if you provide the construction heat, the JVM will not add constructor. therefore, if you do not provide the default constructor to book, the IOC container will report the error cocould not instantiate Bean class [model. book]: no default constructor
Found; you can test it yourself.
Constructor injection:If we specify a constructor for the book, such:

Public book (string ID, string name, string author, float price) {<br/> This. id = ID; <br/> This. name = Name; <br/> This. author = author; <br/> This. price = price; <br/>}< br/> // ignore getter setter
You can configure the bean as follows:
<Bean id = "mybook1" class = "model. book "> <br/> <constructor-Arg Index =" 0 "value =" 000002 "/> <br/> <constructor-Arg Index =" 1 "value =" Thinking in Java "/> <br/> <constructor-Arg Index =" 2 "value =" Bruce Eckel "/> <br/> <constructor-Arg Index =" 3 "Value = "2222"/> <br/> </bean>
Note that the order of the constructed parameters must be the same as that of the constructor, because the constructor can be composed of multiple.

Factory method injection:If we provide a factory dedicated to book production for book, such as a non-static Factory:
Package Model. factory; <br/> Import model. book; <br/> public class bookfactory {<br/> Public book createjavatek () {<br/> book B = New Book (); <br/> B. setid ("001"); <br/> B. setname ("thinking in Java"); <br/> B. setauthor ("Bruce Eckel"); <br/> B. setprice (12.3f); <br/> return B; <br/>}< br/>

You can configure a book bean in this way;
<Bean id = "bookfactory" class = "model. factory. bookfactory "/> <br/> <bean id =" mybook2 "factory-bean =" bookfactory "factory-method =" createjavatek "/>
Of course, if the factory method is static, the configuration is simpler, but a little mysterious.
First, add a static method for bookfactory:
Package Model. factory; <br/> Import model. book; <br/> public class bookfactory {<br/> Public book createjavatek () {<br/> book B = New Book (); <br/> B. setid ("001"); <br/> B. setname ("thinking in Java"); <br/> B. setauthor ("Bruce Eckel"); <br/> B. setprice (12.3f); <br/> return B; <br/>}</P> <p> Public static book create () {<br/> return New Book ("www", 0.0f); <br/>}< br/>}
Configure book Bean:
<Bean id = "mybook3" class = "model. Factory. bookfactory" factory-method = "CREATE"/>,
This bean gets the book object instead of bookfactory.

Automatic Assembly:That is, the attributes of a bean can be matched by the container itself, and autowire can be automatically assembled to get "bytype" or "byname ";

Annotation injection: After 3.0, you can enable annotation so that the container can scan the components under the specified package and assemble the components. The annotations supported include @ component, @ repository, @ service, @ controller, @ brief wired...

Bean dependency:One of the most important concepts of spring: dependency injection, so bean configuration must reflect this feature. If a Class A uses another class B, A depends on B, for example, the person class depends on date.

Package Model; </P> <p> Import Java. util. date; </P> <p> public class person {<br/> private string name; <br/> private char sex; <br/> private date birthday; </P> <p> Public date getbirthday () {<br/> return birthday; <br/>}< br/> Public void setbirthday (date birthday) {<br/> This. birthday = birthday; <br/>}< br/> Public String getname () {<br/> return name; <br/>}< br/> Public void setname (string name) {<br/> This. name = Name; <br/>}< br/> Public char getsex () {<br/> return sex; <br/>}< br/> Public void setsex (char sex) {<br/> This. sex = sex; <br/>}</P> <p> Public String tostring () {<br/> return "name:" + name + "/nsex: "+ sex +"/nbirthday: "+ birthday. tolocalestring (); <br/>}</P> <p>Configuration:
<Bean id = "DT" class = "Java. util. date "> </bean> <br/> <bean id =" person "class =" model. person "> <br/> <property name =" name "value =" sunxing007 "/> <br/> <property name =" sex "value =" M "/> <br/> <property name = "Birthday" ref = "DT"/> <br/> </bean>
RefIs to refer to another bean.

Set injection:For example, class:
Javatekstore
Package Model; <br/> Import Java. util. *; <br/> public class javatekstore {<br/> // normal book <br/> private list commonbooks; <br/> // bestselling book <br/> private set favorites; <br/> // ing of publisher Abbreviation and full name <br/> private map publishermappings; </P> <p> public list getcommonbooks () {<br/> return commonbooks; <br/>}</P> <p> Public void setcommonbooks (list commonbooks) {<br/> This. commonbooks = commonbooks; <br/>}</P> <p> Public set getfavorites () {<br/> return favorites; <br/>}</P> <p> Public void setfavorites (set favorites) {<br/> This. favorites = favorites; <br/>}</P> <p> public map getpublishermappings () {<br/> return publishermappings; <br/>}</P> <p> Public void setpublishermappings (MAP publishermappings) {<br/> This. publishermappings = publishermappings; <br/>}</P> <p>

The configuration is as follows:
<Bean id = "javatekstore" class = "model. javatekstore "> <br/> <property name =" commonbooks "> <br/> <list> <br/> <ref bean =" mybook1 "/> <br/> <ref bean = "mybook2"/> <br/> <ref bean = "mybook3"/> <br/> </List> <br/> </property> <br/> <property name = "favorites"> <br/> <set> <br/> <ref bean = "mybook1"/> <br/> <ref bean = "mybook2" /> <br/> <ref bean = "mybook3"/> <br/> </set> <br/> </property> <br/> <property name =" publishermappings "> <br/> <map> <br/> <Entry key =" Phei "value =" Publishing House of electronics industry "/> <br/> <Entry key = "CMP" value = "China Machine Press"/> <br/> <Entry key = "PTP" value = "post and Telecom Press"/> <br/> <Entry key -ref = "mybook1" value-ref = "mybook1"/> <br/> </map> <br/> </property> <br/> </bean>

Mybook1, mybook2, and mybook3 are the book beans we injected earlier.
Bean scope:Bean has five scopes:
Singleton, prototype, request, session, globalsession. The last three are valid under webapplicationcontext. The default scope is Singleton;

Let's see <bean id = "DT" class = "Java. util. Date"> </bean>. Test code:
Applicationcontext c = new classpathxmlapplicationcontext ("spring-test.xml"); <br/> date now = (date) C. getbean ("DT"); <br/> system. out. println (now. tolocalstring (); <br/> thread. sleep (1000); <br/> now = (date) C. getbean ("DT"); <br/> system. out. println (now. tolocalstring (); <br/>

The two prints have the same time, because the default scope is Singleton, which is equivalent

<Bean id = "DT" class = "Java. util. Date" Scope = "Singleton"> </bean> because Singleton is instantiated only once;

If you change it to <bean id = "DT" class = "Java. util. Date" Scope = "prototype"> </bean>, the two results are different.
Singleton bean can also specify the lazy-init attribute,
<Bean id = "DT" class = "Java. util. Date"Lazy-init= "True"> </bean>, indicating that the instance is instantiated only when used.

There are two more interesting aspects about Bean injection, which may be used less often, but I have used it in projects.


Method injection:Considering that a prototype bean can be returned from a singleton bean every time, the previous configuration cannot be used because of the scope, but method injection is acceptable. Method injection replaces the results returned by the method. Let's look at an interface:
Package Model; </P> <p> Import Java. util. date; <br/> Public interface timereporter {<br/> Public date getdate (); <br/>}< br/>
Configuration file:
<Bean id = "DT" class = "Java. util. date "Scope =" prototype "> </bean> <br/> <bean id =" Reporter "class =" model. timereporter "> <br/> <lookup-method name =" getdate "bean =" DT "/> <br/> </bean>
Test code:
Applicationcontext c = new classpathxmlapplicationcontext ("spring-test.xml"); <br/> while (true) {<br/> thread. sleep (1, 1000); <br/> timereporter B = (timereporter) C. getbean ("Reporter"); <br/> system. out. println (B. getdate (). gettime (); <br/>}
Although timereporter does not have a method body, using method injection is equivalent to dynamically adding an implementation to getdate. However, you need to add the cglib package to classpath.

Inheritance:Considering that if there are several books, most of their attributes have the same value, but some attributes are different, such as the book color, you can configure a abstract bean, let other beans inherit from it, while other Beans only need to configure a small number of properties. Although the example below has no practical significance, we will not delay understanding. Their names, author and prices are the same, but their numbers are different.
<Bean id = "absbook" class = "model. book "abstract =" true "> <br/> <property name =" name "value =" thinking in Java "/> <br/> <property name =" author "Value = "Bruce Eckel"/> <br/> <property name = "price" value = "2222"/> <br/> </bean> <br/> <bean ID = "mybook4" class = "model. book "parent =" absbook "> <br/> <property name =" ID "value =" 000002 "/> <br/> </bean> <br/> <Bean id = "mybook5" class = "model. book "> <br/> <property name =" ID "value =" 000003 "/> <br/> </bean> </P> <p>

 

Spring configurations are flexible and cannot be comprehensive. More content needs to be reflected in actual projects.

Next, we will learn the advanced features of spring containers.

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.