[Turn] Spring study notes 1- dependency injection (constructor injection, set injection and injection annotations)

What is Dependency Injection

In previous java development, in a class of methods relies on other classes, class is usually dependent on a new class instance and then call a method, this method is too high and the degree of coupling is not easy to test, Spring dependency injection is proposed Thought, i.e. not by the programmer instantiates the class dependent, but we specify new instance and the instance is injected into the object's class needs to help by spring containers .

 

Dependency Injection way

Dependency injection three ways: constructor injection, set injection and injection annotations.

1. constructor injection

Constructor injection to ensure the necessary properties is obtained when the set of Bean instance, and ensures Bean instance may be used after instantiation.

Use:

  1. In the class, without providing setter methods for properties, but the construction of such a method with the need to generate a reference.
  2. Disposed in the bean class configuration file, and configure the constructor, and uses a <constructor-arg> constructor node configuration, the node has four attributes
    • index: injecting property order specified index starting from 0;
    • type: This attribute refers to the type corresponding;
    • ref: reference to the dependent objects;
    • value: When the injection is not dependent on the object, but the basic data types, use value;

Example 1:

Copy the code
public class SpringAction {  
    //注入对象springDao  
    private SpringDao springDao;  
    private User user;  
      
    public SpringAction(SpringDao springDao,User user){  
        this.springDao = springDao;  
        this.user = user;  
        System.out.println("构造方法调用springDao和user");  
    }  
          
    public void save(){  
        user.setName("卡卡");  
        springDao.save(user);  
    }  
}  
Copy the code
Copy the code
    <the bean name = "springAction" class = "com.bless.springdemo.action.SpringAction">   
        <-! (2) create a constructor injection, if the primary class has parameterized constructor need to add this configuration ->   
        <constructor-Arg index = "0" REF = "springDao"> </ constructor-Arg>   
        <constructor-Arg index = ". 1" REF = "User"> </ constructor-Arg>   
    </ the bean>   
    <the bean name = "springDao" class = "com.bless.springdemo.dao.impl.SpringDaoImpl"> </ the bean>   
    <the bean name = "User" class = "com.bless.springdemo.vo.User"> </ the bean>  
Copy the code

Wherein the index parameter indicating the attribute of the bean configuration sequential injection method.

Example 2:

Sometimes they need to be used in combination to determine the type and index matching items and correspondence between the parameters of the constructor, see the following code.

Copy the code
public Car(String brand, String corp,double price){
    this.brand=brand;
    this.corp=corp;
    this.price=price;
}

public Car(String brand, String corp,int maxSpeed){
    this.brand=brand;
    this.corp=corp;
    this.maxSpeed=maxSpeed;
}
Copy the code

 Here, Car has two constructors overloaded, they have the three parameters. In view of this situation, according to the configuration parameters into the index and difficult to meet the requirements, then the need for joint use <constructor-arg> the type and index to solve the problem

Copy the code
<! - Constructor injection (correspondence relationship is determined by the type and position of the reference index) -> 
<! - the corresponding public Car (String brand, String corp , int maxSpeed) Constructor -> 
<the bean ID = "Car3 "class =" com.spring.model.Car ">   
    <constructor Arg-index =" 0 "type =" java.lang.String "value =" Benz "> </ Arg-constructor> 
    <constructor-index = Arg" 1 "type =" java.lang.String "value =" China FAW "> </ Arg-constructor> 
    <constructor Arg-index =" 2 "type =" int "value =" 200 is "> </ Arg-constructor> 
</ bean>
Copy the code

For the potential configurations are the same as the ambiguity number of different types of parameters caused, Spring container may start correctly and does not give the error message, it uses a random matching constructor instantiates Bean, the function may be selected and configured not desired by the user. Therefore, we must be particularly careful to avoid potential errors.

 

2.set injection

Bean set injection requires a default constructor, and providing a corresponding Setter for the property to be injected.

Spring first call the default constructor Bean Bean instantiation object, and then calls the attribute value Setter injection method by way of reflection.

Bean assumed display defines a parameterized constructors, you need to provide a default constructor with no parameters, exception will be thrown when using injection property. 

Example 1:

Copy the code
com.bless.springdemo.action Package;   
public class SpringAction {   
        // injection objects springDao   
    Private SpringDao springDao;   
        SET // method must write the object being injected   
    public void setSpringDao (SpringDao springDao) {   
        this.springDao = springDao;   
    }   
  
    public void OK () {   
        springDao.ok ();   
    }   
}  
Copy the code
<! - the bean configuration, the configuration of such a spring management ->   
    <the bean name = "springAction" class = "com.bless.springdemo.action.SpringAction">   
        - (. 1) dependency injection, the current configuration <! class corresponding properties ->   
        <property name = "springDao" REF = "springDao"> </ property>   
    </ the bean>   
   <the bean name = "springDao" class = "com.bless.springdemo.dao.impl.SpringDaoImpl "> </ bean>

No longer uses the "constructor-arg" but rather "property" attribute.

 

3. Notes injection

Notes injection actually use annotations manner set constructor injection or implantation.

spring2.5 began offering based annotation (Annotation-based) configuration, we can complete dependency injection annotations by the way. Or may be used in the Java code @Resource @Autowired annotation manner via injection line.

Although @Resource and @Autowired could come to rely on the completion of the injection, but there is a difference between them:

  1. @Resource default is to assemble injected by name, only if can not find a name that matches the type of bean will be assembled in accordance with the injection;
  2. @Autowired default injection assembly according to the type of, if you want to turn with injection by name, it is necessary to use in combination with @Qualifier;
  3. @Resource annotation is provided and J2EE, and @Autowired is provided by Spring;

example:

Copy the code
com.bless.springdemo.action Package;   
public class SpringAction {   
        // injection objects springDao 
    @Resource 
    Private SpringDao springDao;   
        // set methods need not be injected to write the object, spring will help you GET / set 
       
    public void OK () {   
        springDao.ok ();   
    }   
}  
Copy the code
<context: Annotation-config /> 

<the bean name = "springAction" class = "com.bless.springdemo.action.SpringAction"> <- - no need to configure properties, @ Resource default injection assembly according to the name!> </ the bean> <the bean name = "springDao" class = "com.bless.springdemo.dao.impl.SpringDaoImpl"> </ the bean>

<Context: annotation-config /> effect is on the annotation.

@Autowired the same way, but in accordance with the type of default injection assembly.

 

supplement:

@Autowired can annotate fields, methods and constructors. Then the member variables and constructor comments, what difference does it make? 

First look at the following piece of code:

Copy the code
@Autowired
private User user;
private String school;

public UserAccountServiceImpl(){
    this.school = user.getSchool();
}
Copy the code

The code execution will be error, because the Java class constructor runs first , then give the user annotation injection @Autowired value, so in the implementation of the method of construction, it will error.

The solution is to use constructor injection, as follows:

Copy the code
private User user;
private String school;

@Autowired
public UserAccountServiceImpl(User user){
    this.user = user;
    this.school = user.getSchool();
}
Copy the code

 

Guess you like

Origin www.cnblogs.com/gaobing1252/p/11110655.html