Automatic assembly of Spring frame

Source: Internet
Author: User

The Spring IOC container understands the configuration information of the bean in the container through the Java reflection mechanism, which includes the structure of the method and the information of the property, and it is for this reason that the spring container can automatically assemble the bean by some sort of rule. It is not necessary to configure it by explicit means.


I. Automatic assembly type: The Spring IOC container can automatically assemble association relationships between collaborative beans. Therefore, it is possible to automatically enable spring to specify bean collaboration (other dependent beans) by examining the contents of the Beanfactory, as described in the following 4 types:

1.byName type: Automatically assembled according to the attribute name. This type examines the container and finds the bean that is exactly the same as the property by name and automatically assembles it with the property.

Note: When using the byname auto-assemble type, the set () method must be provided for the property name that you are setting, or an exception will be reported when you start spring.

An example is attached below:

(1). The first step is to create a new Java project with the project name Spring_byname and then configure the spring environment.


(2). The second step, create a new people class, put under the Com.bean package, declare three properties, respectively Name,age,sex, and generate its setxxx () and GetXXX () method, write a method get (), used to output people each property value, See the code in detail, as follows:

<pre class= "java" name= "code" >package Com.bean;public class People {private String name;private int age;private Str ing sex;public String getName () {return name;} public void SetName (String name) {this.name = name;} public int getage () {return age;} public void Setage (int.) {this.age = age;} Public String Getsex () {return sex;} public void Setsex (String sex) {this.sex = sex;} public void Get () {System.out.print ("name:" + name); System.out.print (", Ages:" + age); System.out.print (", Gender:" + Sex);}}


(3). The third step, create a new student class, also placed under the Com.bean package, declare the course course this property and the above people class object properties, and generate properties of the setxxx () and GetXXX () method, write a Get () method, The output course this property value and calls the Get () method in the People class, with the following code:

Package Com.bean;public class Student {private String course;private people people;public String GetCourse () {return cours e;} public void Setcourse (String course) {this.course = course;} Public People GetPeople () {return people;} public void Setpeople (People people) {this.people = people;} public void Get () {System.out.println ("Student's Course:" + course);p eople.get ();}}


(4). Fourth step, open the configuration file Applicationcontext.xml file, only need to start the automatic assembly by Autowire property set to ByName in the <bean> tab, as shown in the following code:

<?xml version= "1.0" encoding= "UTF-8"? ><beansxmlns= "Http://www.springframework.org/schema/beans" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:p= "http://www.springframework.org/schema/p" xsi: schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-3.0.xsd "><bean id=" People "class=" com.bean.People "><property name=" name "value=" Zhang San "> </property><property name= "Age" value= "all" ></property><property name= "sex" value= "male" ></ Property></bean><bean id= "Student" class= "com.bean.Student" autowire= "byname" ><property name= " Course "Value=" Java programming ></property></bean></beans>

Where the name specified in the <property> tag corresponds to the property name one by one in the class, then the ByName automatic assembly type is used in the student bean. Then the id attribute value in Peoplebean must match the People object property name declared in the Student Class!


(5). The fifth step, write a test class tests, also placed under the Com.bean package, which gets the load configuration file, and then through the ApplicationContext object get student This bean, and then call the Bean object's Get () method, The specific code is as follows:

Package Com.bean;import Org.springframework.context.applicationcontext;import Org.springframework.context.support.classpathxmlapplicationcontext;public class Test {public static void main (String [] args) {ApplicationContext ac=new classpathxmlapplicationcontext ("Applicationcontext.xml"); Student stu= (Student) Ac.getbean ("Student"); Stu.get ();}}


(6). The sixth step, the operation effect is as follows:

This people the Bean's three attribute values are automatically assembled into the student of the bean, so the call Get () method also put the people class property values are also lost!


(7). If we change the people in the configuration file to the following example, change the id attribute to People1, as follows:

<bean id= "People1" class= "com.bean.People" ><property name= "name" value= "Zhang San" ></property>< Property Name= "Age" value= "></property><property" name= "Sex" value= "male" ></property></bean >


The other code does not change, after running the test class tests, as shown in:

This gives the null pointer an exception, gets the property name of the people class, so the ID in one bean corresponds to the object property name one by one of another bean, using byname automatic assembly type!

Note: If the above example changes the automatic assembly type to Bytype, it is also possible, even if you people class in the configuration file to configure the Bean ID attribute any line, because this is the type assembled!





2.byType type: If the container has a bean with the same type as the specified property, it will be automatically assembled with that property, and if there are more than one bean of that type, an exception is thrown and the Bytype method cannot be used for automatic assembly; If a matching bean is not found, Then nothing happens.

(1). This is not attached to the example, we can use the above example to set the Autowire property to Bytype, but also run successfully, because it is a type matching, we can change the configuration file as shown below, others do not change:

<?xml version= "1.0" encoding= "UTF-8"? ><beansxmlns= "Http://www.springframework.org/schema/beans" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:p= "http://www.springframework.org/schema/p" xsi: schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-3.0.xsd "><bean id=" P "class=" Com.bean.People "><property name=" name "value=" Zhang San "></ Property><property name= "Age" value= "all" ></property><property name= "sex" value= "male" ></ Property></bean><bean id= "Student" class= "com.bean.Student" autowire= "Bytype" ><property name= " Course "Value=" Java programming ></property></bean></beans>

After running the effect is the same as byname.


(2). If we change the configuration file to resemble the following, we configure two people classes as shown in:

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:p= "http://www.springframework.org/schema/p" xsi: schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-3.0.xsd "><bean id=" P "class=" Com.bean.People "><property name=" name "value=" Zhang San "></ Property><property name= "Age" value= "all" ></property><property name= "sex" value= "male" ></ Property></bean><bean id= "P1" class= "com.bean.People" ><property name= "name" value= "Li Hong" ></ Property><property name= "Age" value= "all" ></property><property name= "Sex" value= "female" ></ Property></bean><bean id= "Student" class= "com.bean.Student" autowire= "Bytype" ><property name= " Course "Value=" Java programming ></property></bean></beans>

An error is reported because we have defined two beans of type people, so we cannot match to which Bean, the error message is as follows:

That is, if the bean is automatically assembled using Bytype, when there are multiple types of beans in the IOC container, it is impossible to determine which bean to choose as the target of automatic assembly, so it throws the above exception information!


(3). Here's a brief look at how spring does the matching entry, and if both Class A and Class B meet either of the following three cases, it can be said that a by type matches B:

~a and B are the same type. ~a is a subclass of B. ~a implements the interface of B.





3.constructor type: Similar to the Bytype type, except that the constructor type is applied to the constructor parameter. Throws an exception if a bean that is consistent with the constructor parameter type is not found in the container.

(1). In fact, the use of constructor automatic assembly, is only through the construction method and automatic assembly.


(2). An example is attached below:

The first step is to create a Java project with the project name Spring_constructor and the spring environment configured.


The second step, create a new man class, the specific code is as follows, do not do analysis, very simple:

Package Com.bean;public class Man {private string name;private string sex;private int age;public string getName () {return Name;} public void SetName (String name) {this.name = name;} Public String Getsex () {return sex;} public void Setsex (String sex) {this.sex = sex;} public int getage () {return age;} public void Setage (int.) {this.age = age;} public void Out () {System.out.println (name); SYSTEM.OUT.PRINTLN (Sex); System.out.println (age);}}


The third step is to create a new building class with the following code:

Package Com.bean;public class Building {private string name;private int floors;private man m;public Building (String name,i NT Floors,man m) {this.name=name;this.floors=floors;this.m=m;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} public int getfloors () {return floors;} public void setfloors (int floors) {this.floors = Floors;} Public Mans Getperson () {return m;} public void Setperson (Mans man) {this.m = mans;} public void Out () {System.out.println (name); System.out.println (floors); M.out ();}}

The building class has a construction method with three parameters.


The fourth step, open the configuration file for configuration, configured as follows:

<?xml Version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns:xsi= "http ://www.w3.org/2001/XMLSchema-instance "xmlns:p=" http://www.springframework.org/schema/p "xsi:schemalocation=" Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd " ><bean id= "man" class= "Com.bean.Man" ><property name= "name" value= "A-LC" ></property>< Property name= "Sex" value= "male" ></property><property name= "age" value= "all" ></property></bean ><bean id= "Building" class= "com.bean.Building" autowire= "constructor" ><constructor-arg index= "0" value= "Kindafford" ></constructor-arg><constructor-arg index= "1" value= "></constructor-arg></bean" ></beans> 

In the configuration file, set the Autowire property to constructor to start the automatic assembly, and then use the <constructor-arg> tag to pass in the parameters of the belt, here only two passes, The object attribute parameters of the last man are passed in by matching the bean with the man type.


The fifth step is to create a new test class with the following code:

Package Com.bean;import Org.springframework.context.applicationcontext;import Org.springframework.context.support.classpathxmlapplicationcontext;import Com.bean.building;public class Test { public static void Main (string[] args) {ApplicationContext ac=new classpathxmlapplicationcontext (" Applicationcontext.xml "); Building b= (Building) Ac.getbean ("Building"); B.out ();}}


The sixth step, after the operation effect is as follows:








Two. Automatic assembly control

1. In a spring application, the number of beans is numerous, so when using automatic assembly, spring throws an exception if multiple occurrences of the container are not functioning properly. For this problem, you can set the bean that does not need to be matched to set whether the bean is an automatically assembled object. When configuring beans in XML format, you can set the Autowire-candidate property of the <bean> element to false so that the container will not consider the bean when it looks for an auto-assembly object, which means that the bean will not be used as an automatic assembly object.


2. If we change the configuration file for the automatic assembly example of the above constructor type to the following, the other code does not change:

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:p= "http://www.springframework.org/schema/p" xsi: schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-3.0.xsd "><bean id=" man "class=" Com.bean.Man "><property name=" name "value=" A-LC "></ Property><property name= "Sex" value= "male" ></property><property name= "age" value= "all" ></ Property></bean><bean id= "Man1" class= "Com.bean.Man" ><property name= "name" value= "A-xg" ></ Property><property name= "Sex" value= "male" ></property><property name= "age" value= "all" ></ Property></bean><bean id= "Building" class= "com.bean.Building" autowire= "constructor" >< Constructor-arg index= "0" value= "Kindafford" ></constructor-arg><constructor-arg index= "1" value= "></" Constructor-arg>&lT;/bean></beans> 

Define two beans of the same type, at which point the IOC container does not know which one to match, so it will report the error:


3. We can set the Autowire-candidate property of a bean that does not need to match the above code to False, as shown in the following code:

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:p= "http://www.springframework.org/schema/p" xsi: schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-3.0.xsd "><bean id=" man "class=" Com.bean.Man "autowire-candidate=" false "><property name=" Name "value=" A-LC "></property><property name=" sex "value=" male "></property><property name=" Age "value=" ></property></bean><bean id= "Man1" class= "Com.bean.Man" ><property name= " Name "value=" A-xg "></property><property name=" sex "value=" male "></property><property name=" Age "value=" ></property></bean><bean id= "Building" class= "com.bean.Building" autowire= " Constructor "><constructor-arg index=" 0 "value=" Kindafford "></constructor-arg><constructor-arg index=" 1 "Value=";</constructor-arg></bean></beans> 


4. The run effect then outputs the information named A-xg, as shown in:






Three. The use of automatic assembly premise: the use of automatic assembly, mainly for convenience, improve work efficiency, but to correct and reasonable use of automatic assembly, you must first understand the advantages and disadvantages of automatic assembly, in order to correctly determine when the use of automatic assembly.

1. The advantages of automatic assembly are as follows:

(1). Automatic assembly can significantly reduce the number of assemblies, so in the configuration of a considerable number of automatic assembly, you can reduce the workload.

(2). Automatic assembly allows the configuration to be synchronized with Java code updates. For example, if you need to add a dependency to a Java class, the dependency will be implemented automatically without the need to modify the configuration. Therefore, it is strongly used in the process of the development of automatic assembly, and when the system tends to stabilize the time to change the way of explicit assembly.


2. Although automatic assembly has these advantages, it is not always possible to use it, as it has some drawbacks:

(1). Although automatic assembly is more magical than explicit assembly, spring avoids guessing when the assembly is ambiguous, because the assembly is ambiguous and may result in unpredictable results, and the association between the objects that spring manages can no longer be clearly documented.

(2). For tools that generate documents based on spring profiles, automatic Assembly will make it impossible for these tools to generate dependency information.


3. When deciding whether to use automatic assembly mode, there is no absolute right or wrong. Considering the actual project is the best approach, for example for large applications, it is not recommended to use automatic assembly. Although automatic assembly can reduce the amount of configuration files, it greatly reduces the clarity and transparency of dependencies. Because the dependency configuration is based on the property name of the source file, this causes the coupling between the bean and the bean to be reduced to the code level, which is not conducive to high-level decoupling.





The above content is only for your study reference, write not good, please forgive me, if there are errors, please point out, thank you!



Automatic assembly of Spring frame

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.