Summary of dependency injection methods in spring

Source: Internet
Author: User

Summary of dependency injection methods in spring

Four Methods of dependency injection in Spring

 

There are three ways to configure dependency injection for a bean in the Spring container:

· Use the setter method of attributes to inject data. This is the most common method;

· Use the constructor for injection;

· Use Filed injection (for annotation ).

 

Use the setter method of the property for Injection

First, configure the injected bean. In the class corresponding to the bean, there should be an object attribute to be injected or an attribute of the basic data type. For example, if UserDAO is injected to the UserBiz class and the basic data type String is injected to UserBiz, set the setter method for the UserDAO object and the String type for dependency injection.

How to configure the bean?

UserDao

 

 

The preceding Code uses the setter method of the attribute for dependency injection.

 

Use constructor Injection

First, inject the PersonDAO and a String type data into the PersonBiz class. In this class, you do not need to set the setter method for the PersonDAO and String data types attributes, however, the constructor of this class needs to be generated as follows:

Public class PersonBizImpl implements PersonBiz {

// Declare the dependent object PersonDAO

PersonDAO personDao = null;

// Declare the basic data type of the dependency

String str = null;

// Generate a construction method without Parameters

Public PersonBizImpl (){

Super ();

}

// Generate the construction method with Parameters

Public PersonBizImpl (PersonDAO personDao, String str ){

Super ();

This. personDao = personDao;

This. str = str;

} Www.bkjia.com

Public void addPerson (){

This. personDao. addPerson ();

System. out. println (str );

}

}

Second, configure the bean of the class in the configuration file and configure the constructor. Node. The node has four attributes:

· Index is an index that specifies the injection attribute, starting from 0. For example, 0 indicates personDao, and 1 indicates str;

· Type refers to the type corresponding to this attribute. For example, Persondao corresponds to com. aptech. dao. PersonDAO;

· Ref is the reference object for guidance;

· Value: value is used when the injection is not a dependent object but a basic data type;

As follows:

 

 

Use Field (Filed) injection (using annotation @ Autowired @ Resource)

In Spring, injection dependent objects can be manually or automatically assembled. in actual application development, manual assembly is recommended, because automatic assembly will generate many unknown situations, developers cannot predict the final assembly results.

There are two ways to manually assemble dependent objects:

One is to configure it under the bean node in the XML file. As mentioned above, the setter method of the attribute is used to inject dependency objects and the constructor method to inject dependency objects.

The other is to use annotations in java code for assembly, add @ Resource or @ Autowired to the code,

How can we use annotations to inject dependency objects to a bena?

First, we need to configure the following information in the Spring container configuration file applicationContext. Xml, which is a template of the Spring configuration file:

 


Xmlns: xsi = http://www.w3.org/2001/XMLSchema-instance
Xmlns: tx = http://www.springframework.org/schema/tx
Xmlns: context = http://www.springframework.org/schema/context
Xsi: schemaLocation = http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
Http://www.springframework.org/schema/context
Http://www.springframework.org/schema/context/spring-context-3.2.xsd
Http://www.springframework.org/schema/tx
Http://www.springframework.org/schema/tx/spring-tx-3.2.xsd>

 

Note: Only the Code with the red part configured can introduce the annotation namespace. Otherwise, an error is returned. The preceding configuration implicitly registers multiple processors for annotation parsing: AutowiredAnnotationBeanPostProcessor, CommonAnnotationBeanPostProcessor, PersistenceAnnotationBeanPostProcessor, and so on.

Second, open The node tells the Spring container to inject dependency objects in Annotation mode. The code in the configuration file is as follows:

......

......

 

Third, configure the bean object in the configuration file as follows:

Fourth, declare a dependency object in the BIZ class that requires dependency injection. You do not need to generate the setter method of the dependency object and add annotations to the object:

Public class UserBizImpl implements UserBiz {

@ Resource (name = userDao)

Private UserDAO userDao = null;

Public void addUser (){

This. userDao. addUser ();

}

}

In Java code, you can use @ Autowired or @ Resource annotation to inject Spring dependencies. The difference between the two is: @ Autowired is assembled by type by default, and @ Resource is assembled by name by default. Only beans with the same name cannot be found will be assembled by type.

For example, we use @ Autowired to annotate the Instance Object of the above Code UserDAO interface. It will go to the Spring container to find the type that matches the UserDAO object, if this type is found, the type is injected into the userdao field;

If @ Resource is used for dependency injection, it first searches for the type that matches the name in the Spring container Based on the specified name attribute, for example, @ Resource (name = userDao ), if this name is not found, it will be searched by type. After it is found, the userDao field will be injected.

We usually use @ Resource.

Using annotation to inject dependent objects no longer requires writing the setter method or constructor method of dependent objects in the code, and no need to configure a large number of dependent objects in the configuration file to make the code more concise, clear and easy to maintain.

In actual development of Spring IOC programming, we recommend using annotation for dependency injection.

Dependency injection-automatic assembly

Spring provides a mechanism for automatic assembly of dependent objects. However, automatic assembly is not recommended in actual applications because automatic assembly will produce unknown conditions and developers cannot predict the final assembly results.

Automatic Assembly is implemented in the configuration file as follows:

You only need to configure an autowire attribute to complete automatic assembly without writing in the configuration file. But the setter method of the dependent object must be generated in the class.

The Autowire attribute values include the following:

· ByType can be assembled by type to search for beans of this type in the container Based on the attribute type. If there are multiple beans, an exception is thrown. If no bean of this type is found, the attribute value is null;

· ByName assembly by name: You can query beans with the same name in the container based on the property name. If no bean name is found, the property value is null;

· The constructor and byType methods are similar. The difference is that they are applied to the constructor parameters. If the bean of the same type as the constructor parameter is not found in the container, an exception is thrown;

· Autodetect determines whether to use constructor or byType for automatic assembly through the introspection mechanism of bean classes. If the default constructor is found, byType is used.

 

 

 

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.