4.spring automatic assembly

Reprinted: https: //blog.kuangstudy.com/index.php/archives/523/

The automatic assembling a .Bean

1. What automatic assembly

  • Automatic spring assembly using a method satisfying dependent bean

  • spring will look for their dependent bean is a bean in the application context.

2.Spring in three bean assembly mechanism, namely:

  1. Explicit arranged in xml;

  2. Explicit arranged in java;

  3. Implicit bean discovery mechanism and automatic assembly.

Here we talk about the third: automated assembly bean.

3.Spring needs to achieve automatic assembly from two angles, or that two operations:

  1. Scanning component (component scanning): spring bean automatically find application context created;

  2. Automatic assembly (autowiring): spring automatically satisfy the dependencies between the bean, that is, we are talking about IoC / DI;

Scanning and automatic assembly configuration component composition play great power, so that the display is reduced to a minimum.

It recommended not to use automated assembly xml configuration, and use notes.

4. build project spring-05-Autowired

Entity classes:

Cat.java

public  class Cat {

    public void shout(){
        System.out.println("miao~");
    }
}

Dog.java

public class Dog {

    public void shout(){
        System.out.println("wang~");
    }
}

People.java

public class People {

    private Cat cat;
    private Dog dog;
    private String name;

    public Cat getCat() {
        return cat;
    }

    public  void gill-nets (CAT) {
         this .cat = both;
    }

    public Dog getDog() {
        return dog;
    }

    public void setDog(Dog dog) {
        this.dog = dog;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "People{" +
                "cat=" + cat +
                ", dog=" + dog +
                ", name='" + name + '\'' +
                '}';
    }
}

beans.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xsi:schemaLocation="http://www.springframework.org/schema/beans
 5         https://www.springframework.org/schema/beans/spring-beans.xsd">
 6 
 7     <bean id="cat" class="ustc.wzh.pojo.Cat"></bean>
 8     <bean id="dog" class="ustc.wzh.pojo.Dog"></bean>
 9 
10     <!--1.The original display assembly wording ->
class     <the bean ID = "people". 11="ustc.wzh.pojo.People">
12         <property name="name" value="小王"></property>
13         <property name="cat" ref="cat"></property>
14         <property name="dog" ref="dog"></property>
15     </bean>
16 
17 </beans>

Test class MyTest.java

public class MyTest {


    @Test
    public void test1(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

        People people = context.getBean("people", People.class);

        people.getCat().shout();
        people.getDog().shout();
    }
}

The program automatically modify the assembly

Automatic assembling two main ways:

  • byName: bean's unique id , the container will automatically find the context, if the value Set attribute name and id of the same value bean configuration

  • the byType: bean's unique class , the container will automatically find context, if the same object type name and the type of the bean class is automatically assembled (possibly multiple types of the same name is an error, using the id attribute can be omitted ByType the bean)

byName:

<bean id="people" class="ustc.wzh.pojo.People" autowire="byName">
    <property name="name" value="小王"></property>
</bean>

byType:

<bean id="people" class="ustc.wzh.pojo.People" autowire="byType">
    <property name="name" value="小王"></property>
</bean>

II. Use of automatic assembly annotations

  • jdk1.5 began to support annotations, spring2.5 began full support annotations.

1. Preparation:

Modify beans.xml

<?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:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        HTTPS: // www.springframework.org/schema/beans/spring-beans.xsd 
        HTTP: // www.springframework.org/schema/context 
        HTTPS: // www.springframework.org/schema/context/spring-context. xsd ">

  <-! open comments -> <context:annotation-config/> </beans>

2.@Autowired

  • @Autowired is automatically transferred by type of distribution, it is not supported by id match.

(1) may not need to write to the User class set method, using annotation @Autowired

public class User {
    @Autowired
    private Cat cat;
    @Autowired
    private Dog dog;
    private String str;

    public Cat getCat() {
        return cat;
    }
    public Dog getDog() {
        return dog;
    }
    public String getStr() {
        return str;
    }
}

(2) optimization profile

<context:annotation-config/>

<bean id="dog" class="com.kuang.pojo.Dog"/>
<bean id="cat" class="com.kuang.pojo.Cat"/>
<bean id="user" class="com.kuang.pojo.User"/>

(3) Supplementary

  • @Autowired (required = false) Description: false, the object can be null; true, the object must be present object can not be null.

// If the object is allowed to be null, setting required = false, defaults to true 
@Autowired (= required to false )
 Private Cat CAT;

3.@Qualifier

  • @Autowired according to the type of automatic assembly, the assembly may be automatically coupled @Qualifier manner according byName

  • @Qualifier not be used alone.

(1) Configuration file content, to ensure the presence of the object type. And the name is not the default name of the class!

<bean id="dog1" class="com.kuang.pojo.Dog"/>
<bean id="dog2" class="com.kuang.pojo.Dog"/>
<bean id="cat1" class="com.kuang.pojo.Cat"/>
<bean id="cat2" class="com.kuang.pojo.Cat"/>

(2) If only @Autowired will complain, need @Qualifier

@Autowired
@Qualifier(value = "cat2")
private Cat cat;
@Autowired
@Qualifier(value = "dog2")
private Dog dog;

4.@Resource

  • @Resource if specified attribute name, attribute byName the press fitting manner lookup;

  • Secondly, then the default byName assembled manner;

  • If the above are not successful, press byType way automatic assembly.

  • Not successful, reported abnormal.

(1) Modify User.java

public  class the User {
     // If the object is allowed to be null, setting required = false, defaults to true 
    @Resource (name = "CAT2" )
     Private Cat CAT;
    @Resource
    private Dog dog;
    private String str;
}

(2) Modify beans.xml

<bean id="dog" class="com.kuang.pojo.Dog"/>
<bean id="cat1" class="com.kuang.pojo.Cat"/>
<bean id="cat2" class="com.kuang.pojo.Cat"/>

<bean id="user" class="com.kuang.pojo.User"/>

5. Summary

@Autowired and @Resource similarities and differences:

  1. @Autowired assembly can be used with @Resource bean. Can be written in the field, or write on the setter methods.

  2. Default fitting @Autowired by type (belonging to the spring specifications), by default in claim dependent objects must be present, if you want to allow null values, can set its required property is false, such as: @Autowired (required = false), if we want assembly may be combined with the name used for annotations @Qualifier

  3. @Resource (forever, the J2EE), assembled in accordance with a default name, which can be specified by the name attribute. If you do not specify a name attribute, when the notes written on the field, take the default field name lookup by name, if the notes written on the attribute setter methods to take default name for assembly. When that matches the name can not be found when assembled in accordance with the type of bean. However, note that if the name attribute if specified, will only be assembled by name.

Their role is injected into the same object with the annotation mode, but a different order of execution. @Autowired first byType, @ Resource to byName.

 

Guess you like

Origin www.cnblogs.com/zhihaospace/p/12324486.html