"Spring" Spring automatic assembly in layman's

Source: Internet
Author: User

Lin Bingwen Evankaka Original works. Reprint please specify the source Http://blog.csdn.net/evankaka

set injection and construction injection are sometimes cumbersome to configure. So the framework is designed to improve development efficiency by providing automatic assembly functionality and simplifying configuration. The spring framework does not support automatic assembly by default, and you need to modify the Autowire property of the <bean> tag in the spring configuration file to use Auto-assembly . The Automatic assembly attribute has 5 values, each representing a different meaning.

1, ByName

When you get a target object from a spring environment, the properties in the target object look for the id attribute value of the <bean> tag in the entire spring environment based on the name. If there is the same, then get this object, implement the association.

The entire spring environment: represents all of the spring configuration files in the lookup, then the ID can not be duplicated.

2, Bytype

When a target object is obtained from a spring environment, the properties in the target object find the class attribute value of the <bean> tag based on the type in the entire spring environment. If there is the same, then get this object, implement the association.

Disadvantage: If there are multiple bean objects of the same type, an error occurs.

If the property is a single type of data, an error occurs when finding multiple associated objects.

If an attribute is an array or a collection (generic) type, then finding multiple associated objects does not occur unexpectedly.

3, constructor (3.x or above is not available)

Using the construction method to complete the object injection is actually based on the parameter type of the construction method to find the object, which is equivalent to using Bytype. throws an exception if it is not found

4, AutoDetect

Automatic selection: If the object does not have a method of constructing without parameters, the automatic assembly method of constructor is automatically selected for construction injection. If the object contains a parameterless construction method, the automatic assembly method of Bytype is automatically selected for setter injection.

5, no

by default, it is not automatically assembled and manually set by the "ref" attribute.

The Autowire property of the <bean> tag, which is responsible for automatic assembly <bean> label definition JavaBean properties. This saves many of the tag code that configures the JavaBean property, making the code neat and beautiful. However, it also has a negative effect, that is, after using automatic assembly, it is not possible to read from the configuration file what attributes JavaBean needs. There are many incorrect assembly problems with automatic assembly, such as the wrong Mount property, the "Bytype" property, and the "constructor" property, which cannot be judged for the same type parameters. Of course, the combination of automatic assembly and manual assembly can also solve this problem. Here's an example of how to use automatic assembly.

First create a student class Student, define the attributes such as number, name, gender, age, and add the

The set () and get () methods that should be used. The program code is as follows.

Package Com.autobean;public class Student {private string id;private string name;private int age;private string sex;public String GetID () {return ID;} public void SetID (String ID) {id = ID;} 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;}}
Also create a teacher class Teacher, define attributes such as name, gender, and age, and add the corresponding set () and get () methods. The program code is as follows.
Package Com.autobean;public class Teacher {private String name;private int age;private string 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;}}

Create a teaching archive class Teachfile, define the Teacher and Student two properties, and add the print () method. Information that is used to output teachers and students. The program code is as follows.

package Com.autobean;public class Teachfile {private Teacher teacher;private Student student;public teachfile () {}public Teachfile (Teacher Teacher, Student Student) {this.teacher = Teacher;this.student = Student;} Public Student getstudent () {return this.student;} public void Setstudent (Student student1) {this.student = Student1;} Public Teacher Getteacher () {return Teacher;} public void Setteacher (Teacher Teacher) {this.teacher = Teacher;} public void print () {System.out.println ("------Teacher information------"); System.out.println ("Name:" + teacher.getname ()); System.out.println ("Age:" + teacher.getage ()); System.out.println ("Gender:" + teacher.getsex ()); System.out.println (); SYSTEM.OUT.PRINTLN ("------Student information------"); System.out.println ("Study No.:" + Student.getid ()); System.out.println ("Name:" + student.getname ()); System.out.println ("Age:" + student.getage ()); System.out.println ("Gender:" + student.getsex ());}} 

Define and assign a value to the class you just created in the configuration file Applicationcontext.xml. Among them, the Teachfile class adopts automatic assembly. The program code is 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.2.xsd "><bean id=" student "class=" com.autobean.Student "> <property name=" id "value=" 80 "/&     Gt <property name= "name" value= "King"/> <property name= "age" value= "all/> <property name=" Sex "value=" Male "/> </bean><bean id=" teacher "class=" Com.autobean.Teacher "> <property name=" name "value=" ho Teacher "/  > <property name= "Age" value= "/> <property name=" Sex "value=" female "/> </bean><!-- By default, the Bean is assembled through ' ref '--><bean id= "TeachFile1" class= "Com.autobean.TeachFile" > <property name= "Teacher" ref= "Teacher"/> <property name= "student" ref= "student"/></bean> <!--According to byname automatic Assembly bean--><bean id= "teachFile2" autowire= "ByName" class= " Com.autobean.TeachFile "/> <!--auto Assemble bean--<bean id=" TeachFile3 "autowire=" Bytype "class= by Bytype Tobean. Teachfile "/> <!--auto-assemble bean--><bean id=" teachFile4 "autowire=" constructor constructor "class=" Com.autobean.TeachFile "/></beans>

The Student class and the Teacher class are defined in this configuration file and assigned values for name, age, and gender attributes. When defining the Teachfile class, no arguments are passed, but the properties required for the Teachfile class are automatically configured with the Autowire property. Write a main class Printinfo class below to output the archive information. The program code is as follows.

Package Com.autobean;import Org.springframework.beans.factory.beanfactory;import Org.springframework.beans.factory.xml.xmlbeanfactory;import Org.springframework.core.io.ClassPathResource; Import Org.springframework.core.io.resource;public class Printinfo {public static void main (string[] args) {Resource res = new Classpathresource ("Applicationcontext.xml"); beanfactory bf = new Xmlbeanfactory (res); Teachfile TF1 = (teachfile) bf.getbean ("TeachFile1"); Teachfile TF2 = (teachfile) bf.getbean ("TeachFile2"); Teachfile tf3 = (teachfile) bf.getbean ("TeachFile3"); Teachfile Tf4 = (teachfile) bf.getbean ("TeachFile4"); System.out.println ("By default, the Bean is assembled by ' ref '); Tf1.print (); SYSTEM.OUT.PRINTLN ("Automatic assembly of Beans according to ByName"); Tf2.print (); SYSTEM.OUT.PRINTLN ("Automatic assembly of Beans according to Bytype"); Tf3.print (); System.out.println ("Automatically assemble beans according to constructor"); Tf4.print ();}}

Output Result:

April 02, 2015 8:16:48 pm Org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadbeandefinitions
Info: Loading XML Bean Definitions from class path resource [Applicationcontext.xml]
By default, the Bean is assembled by ' ref '
------Teacher Information------
Name: Mr. Ho
Age: 43
Gender: Female

------Student Information------
Study No.: 80
Name: King
Age: 23
Gender: Male
Automatic assembly of beans according to ByName
------Teacher Information------
Name: Mr. Ho
Age: 43
Gender: Female

------Student Information------
Study No.: 80
Name: King
Age: 23
Gender: Male
Automatic assembly of beans according to Bytype
------Teacher Information------
Name: Mr. Ho
Age: 43
Gender: Female

------Student Information------
Study No.: 80
Name: King
Age: 23
Gender: Male
Automatic assembly of beans according to constructor
------Teacher Information------
Name: Mr. Ho
Age: 43
Gender: Female

------Student Information------
Study No.: 80
Name: King
Age: 23
Gender: Male


In the configuration file Appcontext.xml of the above instance, the Teachfile class uses 4 kinds of assembly, which will Teacher
Class and the Student class are injected into the corresponding property. The syntax format is as follows.

<bean autowire= "byname" id= "Teachfile" class= "Teachfile"/>
The type "ByName" is specified in the Autowire property. The Autowire property supports a total of 5 assembly types, the following
Describes the usage of each assembly type, respectively.
(1) No:autowireUsing the default values, automatic assembly is used. Other beans must be referenced directly using ref, which increases the readability of the code and is not easy to make mistakes.
(2) ByName:Automatic assembly is distinguished by attribute name. Find the same JavaBean in the container as the JavaBean property name and assemble it automatically into JavaBean. If you use the above example to explain, the instance object Teachfile of the Teachfile class contains two attributes, respectively, instance objects of the Teacher class and Student class, and instances of these two classes are already defined in the configuration file. When you define an Teachfile instance, you specify that the automatic assembly type is "ByName", and the container automatically looks for the attributes required by the Teachfile instance (that is, teacher and student two JavaBean) and injects it into the teachfile instance. Such automatic assembly types have the potential to incorrectly assemble JavaBean, and if the configuration file defines JavaBean with the same type of JavaBean property that needs to be automatically assembled, it incorrectly injects different types of JavaBean. The reader can modify the configuration file in the above example to keep the type of student and teacher two JavaBean, and change the name to a different one, this problem occurs. Automatic assembly does not solve the problem at this point, and can only be used to specify which JavaBean to assemble by mixing manual assembly.
(3) Bytype:Automatic assembly is distinguished by attribute type. The container automatically looks for the definition of the same JavaBean as the JavaBean property type and injects it into the JavaBean that needs to be automatically assembled. You can also achieve the same result if you modify the type of automatic assembly configured JavaBean above to Bytype. This type of automatic assembly can also occur where automatic assembly is not possible. For example, if you add an implementation object for the student class or Teacher class again in the configuration file, the Bytype automatic assembly type will not automatically identify which JavaBean to assemble. and throws a Org.springframework.beans.factory.UnsatisfiedDependencyException exception. To resolve this
Problem, you can only specify which JavaBean to assemble by mixing manually with the assembly.
(4) constructor:Automatic assembly by constructing the parameter type of the method. This type causes the container to automatically look for beans with the same parameter type as the JavaBean constructor, and inject them into the JavaBean that require automatic assembly. It
The same unrecognized automatic assembly exists with the Bytype type.
(5) Autudetect:This is the last automatic assembly type, which is automatically assembled using the constructor method and then using the Bytype method. Of course it also has the same anomalies as Bytype and constructor. Built
When using automatic assembly, the problem-prone JavaBean is injected using manual assembly to inject the dependency property
Lin Bingwen Evankaka original works. Reprint please specify the source Http://blog.csdn.net/evankaka

"Spring" Spring automatic assembly in layman's

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.