Summary of dependency injection methods in spring

Source: Internet
Author: User

Four ways to rely on injection in spring


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

· This is the most common way to inject a setter method that uses attributes;

· Using a constructor injection;

· Use filed injection (for annotation mode).

Use the setter method of the property to inject

The first thing to configure is the injected bean, which in the corresponding class of the bean should have the attributes of the object or the base data type to be injected. For example, to inject Userdao for the Userbiz class and inject the basic data type string for Userbiz, then set the setter method for the Userdao object and the string type. for dependency injection.

How do I configure the bean?

<bean id= "userbiz" class= "Com.text.biz.impl.UserBizImpl" >

<property name= "Userdao" >

<ref>userDao</ref>

</property>

</bean>

The above is a dependency injection in a way that uses the setter method of the property.

Using the constructor to inject

First, inject Persondao and a string type of data into the Personbiz class, where you do not have to set the setter method for the Persondao property and the property of the string data type, but you need to build the class's construction method Following

public class Personbizimpl implements Personbiz {

Declaring "dependent objects" Persondao

Persondao Persondao = null;

Declaring "dependent basic data Types"

String str = NULL;

Generating an parameterless construction method

Public Personbizimpl () {

Super ();

}

Building a method with parameter construction

Public Personbizimpl (Persondao Persondao, String str) {

Super ();

This.persondao = Persondao;

This.str = str;

}

public void Addperson () {

This.personDao.addPerson ();

System.out.println (str);

}

}

Second, you configure the Bean for the class in the configuration file and configure the constructor to use the <constructor-arg> node in the configuration builder, which has four properties:

· Index is indexed, specifying the injected property, starting from 0, such as: 0 for persondao,1 for str attribute;

· type refers to the types of the property, such as Persondao corresponding to the Com.aptech.dao.PersonDAO;

· ref refers to a referenced dependent object;

· value is used when injecting not the dependent object, but the basic data type;

As follows:

<!--Use the constructor to configure dependency injection--

<bean id= "Persondao" class= "Com.aptech.dao.impl.PersonDAOImpl" ></bean>

<bean id= "personbiz" class= "Com.aptech.biz.impl.PersonBizImpl" >

<constructorargindex= "0" type= "Com.aptech.dao.PersonDAO" ref= "Persondao" ></constructor-arg>

<constructor-arg index= "1" value= "Spring Learning" ></constructor-arg>

</bean>

Use field (Filed) injection (annotated @Autowired @Resource)

In spring, injection-dependent objects can be manually assembled or automatically assembled, and manual assembly is recommended in real-world application development because automatic assembly creates many unknowns, and developers cannot foresee the final assembly results.

The manual assembly of dependent objects is divided into two ways:

One is in an XML file, by configuring it under a bean node, and as described above, injecting a dependent object with the setter method of the property and injecting the dependent object using the constructor method.

The other is to assemble in Java code using annotations, adding @Resource or @Autowiredin the code,

How do you use annotations to inject dependent objects into a Bena?

First, we need to configure the following information in the Spring container's configuration file, Applicationcontext.xml file, which is a template for a spring 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"
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 ">
</beans>

Note: only the code that is configured with the Red section can introduce the annotated namespace, otherwise an error is made. The above configuration implicitly registers multiple processors that parse the annotations: Autowiredannotationbeanpostprocessor, Commonannotationbeanpostprocessor, Persistenceannotationbeanpostprocessor and so on.

Next, open the <context:annotation-config> node in the configuration file and tell the spring container to inject the dependent object in the annotated way, and its code in the configuration file is as follows:

<beans>

......

<context:annotation-config></context:annotation-config>

......

</beans>

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

<bean id= "Userdao" class= "Com.springtest.dao.impl.UserDAOImpl" ></bean>

<bean id= "userbiz" class= "Com.springtest.biz.impl.UserBizImpl" ></bean>

In the Biz class where dependency injection is required, declare a dependent object without generating a setter method for the dependent object and annotate 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 annotations for spring Dependency injection. The difference is that @Autowired is assembled by type by default, @Resource is assembled by name by default and is assembled by type when no bean matching the name is found.

For example: We use @autowired to annotate the instance object of the code Userdao interface above, and it will go to the spring container to find the type that matches the Userdao object, and if it is found, inject that type into the Userdao field;

If you use @resource for dependency injection, it will first look for the type that matches the name in the spring container based on the specified name property, for example: @Resource (name= "Userdao"), and if the name is not found, it will be searched by type, and after it is found, The field Userdao is injected.

Usually we use @resource.

Using annotations to inject dependent objects without having to write the setter method of the dependent object in the code or the constructor method of the class, and without configuring a large number of dependent objects in the configuration file, makes the code more concise, clear and easy to maintain.

It is recommended to use annotations for dependency injection in the actual development of spring IOC programming.

Dependency Injection-Automatic assembly

Spring provides a mechanism for automating the assembly of dependent objects, but it is not recommended to use automatic assembly in practical applications, because automatic assembly creates an unknown situation and the developer cannot foresee the final assembly result.

Automatic assembly is implemented in the configuration file, as follows:

<bean id= "* * *" class= "* * *" autowire= "Bytype" >

You only need to configure one Autowire property to complete the automatic assembly, no more write <property> in the configuration file, but in the class you want to build the setter method of the dependent object.

The Autowire property values are as follows:

bytype assembly by type you can find the type-matching bean in the container based on the property type, if there are more than one, an exception is thrown, and if not found, the property value is null;

byname by name the bean with the same property name can be queried in the container based on the name of the property, and if not found, the property value is null;

Constructor is similar to the bytype approach, where it is applied to the constructor parameter, and throws an exception if no bean is found in the container that matches the constructor parameter type.

AutoDetect uses the Bean class's introspection mechanism (introspection) to determine whether to automate assembly using constructor or Bytype. If you find the default constructor, you will use the Bytype method.

Spring Automatic injection Detailed view: Spring Dependency Injection


Summary of dependency injection methods in spring

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.