6、Bean Automatic assembly of

6.1 Automatic assembly instructions

  • Automatic assembly is the use of spring Satisfy bean A method of dependency

  • spring In the context of an application bean Look for what it depends on bean.

Spring in bean Three kinds of assembly mechanism based on virtual reality :

  1. stay xml Explicitly configure ;

  2. stay java Explicitly configure ;

  3. implicit bean Discovery mechanism and automatic assembly .

Here's the main thing : Automated assembly bean.

Spring The automatic assembly needs to be realized from two aspects , Or two operations :

  1. Component scan (component scanning):spring It will automatically discover the bean;

  2. Automatic assembly (autowiring):spring Automatically meet bean Dependence between , That's what we're talking about IoC/DI;

The combination of component scanning and automatic assembly is powerful , The display configuration is minimized .

6.2 Test environment construction

1、 Create a new project

2、 Create two new entity classes ,Cat Dog There's a way to call it

public class Cat {
public void shout() {
System.out.println("miao~");
}
} public class Dog {
public void shout() {
System.out.println("wang~");
}
}

3、 Create a new user class User

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

4、 To write Spring The configuration file

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="dog" class="com.chen.pojo.Dog"/>
<bean id="cat" class="com.chen.pojo.Cat"/>

<bean id="user" class="com.chen.pojo.User">
<property name="cat" ref="cat"/>
<property name="dog" ref="dog"/>
<property name="str" value="chen"/>
</bean>
</beans>

5、 test

public class MyTest {
@Test
public void testMethodAutowire() {
ApplicationContext context = newClassPathXmlApplicationContext("beans.xml");
User user = (User) context.getBean("user");
user.getCat().shout();
user.getDog().shout();
}
}

6.3 byName Automatic assembly

autowire byName ( Automatic assembly by name )

Due to manual configuration xml In the process , Errors such as missing letters and case letters often occur , And you can't check it , Reduce the efficiency of development .

Using automatic assembly will avoid these mistakes , And make the configuration simple .

test :

1、 modify bean To configure , Add a property autowire="byName"

<bean id="user" class="com.chen.pojo.User" autowire="byName">
<property name="str" value="chen"/>
</bean>

2、 The test again , The result is still output successfully !

3、 We will cat Of bean id It is amended as follows cat11

4、 The test again , Execution time null pointer  java.lang.NullPointerException . Because press byName Rules don't match set Method , real setCat It's not implemented , The object is not initialized , Therefore, a null pointer error will be reported when calling .

Summary :

When one bean Node with autowire byName When the properties of the .

  1. Will find all of the set Method name , for example setCat, Gain will set Remove and lower case initial strings , namely cat.

  2. Go to spring Container to find if there is this string name id The object of .

  3. If there is , Take it out and inject it ; without , The null pointer exception is reported .

6.4 byType Automatic assembly

autowire byType ( Automatic assembly by type )

Use autowire byType First of all, we need to make sure that : Objects of the same type , stay spring The only one in the container . If it's not the only one , It will report more than one exception  NoUniqueBeanDefinitionException .

test :

1、 take user Of bean Change the configuration : autowire="byType"

2、 test , Normal output

3、 Sign up for a cat Of bean object !

<bean id="dog" class="com.chen.pojo.Dog"/>
<bean id="cat" class="com.chen.pojo.Cat"/>
<bean id="cat2" class="com.chen.pojo.Cat"/>

<bean id="user" class="com.chen.pojo.User" autowire="byType">
<property name="str" value="chen"/>
</bean>

4、 test , Report errors :NoUniqueBeanDefinitionException

5、 Delete cat2, take cat Of bean Change the name ! test ! Because it's assembled by type , So no exception will be reported , It doesn't affect the final result . Even the id Attributes to remove , It doesn't affect the results .

This is automatic assembly by type .

6.5 Automatic assembly using annotations

Using annotations

jdk1.5 Start supporting annotations ,spring2.5 Start to fully support annotations .

preparation : Use annotation to inject attributes .

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

<!-- Turn on annotation support -->
<context:annotation-config/>

</beans>

@Autowired

  • @Autowired It's automatically assembled by type , I won't support it id matching .

  • Import required spring-aop My bag !

test :

1、 take User Class set Methods to remove , Use @Autowired annotation

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、 At this point, the configuration file content

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

<context:annotation-config/> ​ <bean id="dog" class="com.chen.pojo.Dog"/>
<bean id="cat" class="com.chen.pojo.Cat"/>
<bean id="user" class="com.chen.pojo.User"/>

</beans>

3、 test , Successful output results .

@Autowired(required=false)

explain :false, The object can be null;true, Objects must hold objects , Not for null.

// If the object is allowed to be null, Set up required = false, The default is true
@Autowired(required = false)
private Cat cat;

@Qualifier

  • @Autowired It's automatically assembled according to the type , add @Qualifier According to byName The way of automatic assembly

  • @Qualifier Not to be used alone .

test

1、 Configuration file changes , Ensure that the type exists the object . And the name is not the default name of the class !

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

2、 No addition Qualifier test , Direct error

3、 Add... To the attribute Qualifier annotation

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

test , Output successful .

@Resource

  • @Resource If specified name attribute , Press the attribute first byName How to find the assembly ;

  • Secondly, the default byName Method of assembly ;

  • If none of the above is successful , Then press byType The way of automatic assembly .

  • Don't successful , Abnormal Report .

Entity class :

public class User {
@Resource(name = "cat2")
private Cat cat;
@Resource
private Dog dog;
private String str;
}

xml:

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

Test success .

Delete cat2

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

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

Only annotations are kept on entity classes

@Resource
private Cat cat;
@Resource
private Dog dog;

Test success .

Summary

@Autowired And @Resource similarities and differences :

1、@Autowired And @Resource Can be used to assemble bean. All can be written on the fields , Or in setter On the way .

2、@Autowired Assembly by type by default ( Belong to spring standard ), By default, dependency objects must exist , If you want to allow null value , You can set its required The attribute is false, Such as :@Autowired(required=false) , If you want to use the name assembly, you can combine @Qualifier Use annotations

3、@Resource( Belong to J2EE return ), By default, assemble by name , The name can be given by name Property to specify . If not specified name attribute , When comments are written on fields , By default, the field name is used to search by name , If the note is written in setter Method, the property name is used for assembly by default . When no match can be found for the name bean Assembly according to type . But here's the thing , If name Property once specified , Just assemble by name .

They do the same thing by injecting objects with annotations , But the execution order is different .@Autowired First byType,@Resource First byName.

Spring Study 03 More articles about

  1. Spring Study 03

    One . Review of the previous section 1 annotation ioc operation (1) Using annotations to create objects - Four notes (2) Injecting attributes with annotations - Two notes 2 aop (1)aop principle (2)aop The term - The breakthrough point - enhance - section 3 s ...

  2. spring Study (03) And bean Three ways to instantiate

    bean There are three ways to instantiate stay spring There are three instantiations in bean The way : One . Instantiate with constructor :( One of the common methods used , a key ) Two . Instantiate using static factory methods : 3、 ... and . Use the example factory method to instantiate The first one is . Usage construction ...

  3. Spring Study 03——AOP Demo

    Section class StudentServiceAspect.java package com.su.advice; import org.aspectj.lang.JoinPoint; import org.as ...

  4. Spring learning —— Handwriting Spring Source code V2.0( Realization IOC、D、MVC、AOP)

    Preface In the last article <Spring learning —— Handwriting Spring Source code (V1.0)> in , I realized a Mini Version of Spring frame , In these days , The blogger has read a lot about Spring Source code analysis of the video , Benefited greatly , also ...

  5. spring learning bean Injection mode of property and constructor-arg How to use

    spring learning bean Injection mode of property and constructor-arg How to use . bean Injection mode of : property Injection is :  adopt setxx Methods to inject . construct ...

  6. JavaScript Study 03 JS function

    JavaScript Study 03 JS function Functions are blocks of code wrapped in curly braces , Key words used earlier function: function functionName() { Here's the code to execute } Function parameter Functional ...

  7. Java virtual machine JVM Study 03 Connection process : verification 、 Get ready 、 analysis

    Java virtual machine JVM Study 03 Connection process : verification . Get ready . analysis After the class is loaded , Just enter the connection phase . Connection is to merge the binary data of the class that has been read into the memory into the runtime environment of the virtual machine . There are three steps in the connection phase : verification . Preparation and analysis . class ...

  8. Spring learning AOP Summary post

    AOP( Aspect oriented programming ), It can also be called aspect oriented programming , It's a programming paradigm , It provides another way to consider the program structure, so as to improve the object-oriented programming (OOP). It's going on OOP When developing , It's all based on components ( Such as class ) Development , Then group the components ...

  9. Spring The first one to learn AOP Program

    IOC and AOP yes Spring The two cornerstones of ,AOP( Aspect oriented programming ), It can also be called aspect oriented programming , It's a programming paradigm , It provides another way to consider the program structure, so as to improve the object-oriented programming (OOP). It's going on OOP When developing , It's all based on the right ...

  10. MyEclipse Spring Learning summary three SpringMVC

    MyEclipse Spring Learning summary three SpringMVC One .SpringMVC principle 1.Springmvc The framework is introduced 1)Spring The framework stopped building Web Full functionality of the application MVC modular .Spr ...

Random recommendation

  1. I contribute to open source , Web text extraction ——Html2Article

    Why text extraction Generally do public opinion analysis , Will be involved in the extraction of web content . For analysis , The valuable information is the body part , Most of the time , For the convenience of analysis , You need to get rid of the irrelevant parts of the web page and the text . It can be said that the quality of text extraction , It directly affects ...

  2. DownloadManager

    stay androi in ,volley Suitable for small file acquisition and large concurrency , If you support downloading large files, you can use Android Native DownloadManager.DownloadManager Multi thread download is supported by default . Breakpoint continuation, etc . The base ...

  3. For package management 21 individual Linux YUM command Reprint

    http://flycars001.iteye.com/blog/1949085 YUM What is it ? YUM(Yellowdog Updater Modified) Is an open source command line and graphical software package management ...

  4. ios The basic chapter ( Nine )—— Customize UITabBar

    We talked about that in the last post UITabBarViewController, Let's go on UITabBarViewController How to customize TabBar. Today, I imitated the microblog , Find the bottom tabbar In the middle of the button And others ...

  5. LevelDb Introduction to the series

    Speaking of LevelDb Maybe you don't know , But as IT The engineer , I don't know about the following two great God level engineers , Then your leader is expected to Hold I can't help it. :Jeff Dean and Sanjay Ghemawat. These two are Google Company weight ...

  6. Objective-C Introspection of (Introspection) Summary

    introspection (Introspection) It's a powerful feature of object-oriented languages and environments ,Objective-C and Cocoa Especially rich in this aspect . Introspection is the ability of an object to reveal its own details as a runtime object . These details include ...

  7. Web End js export csv file ( Use a label )

    Preface export file , The most commonly used method is the server side . such as jsp Use in response The way . however , Sometimes you just want to use web Can the front end also export the content on the page ? for instance , Export a table from the page . this ...

  8. LeetCode the second day &amp; On the third day

    leetcode the second day 2017 year 12 month 27 Japan 4.(118)Pascal's Triangle JAVA class Solution { public List<List<Integ ...

  9. Android TextView Common properties

    [ explain ] TextView Is a component used to display text . Here is XML Properties in code , stay java In the code, you can also use " Component name .setXXX() Method setting . Such as ,tv.setTextColor(); [ Belong to ...

  10. external And static Usage of

    One .extern yes C/C++ The scope of functions and global variables is indicated in language ( visibility ) Key words of : It tells the compiler , The declared functions and variables can be used in this function file or other function files . 1. about extern In terms of variables , It's just the sound of a variable ...