Dependency injection 3 ways (xml implementation)

Constructor injection

Constructor injection depends on the implementation of the constructor, and the constructor can be parameterized and parameterless

For example, the constructor is:

public Test(String id,String name){
    this.id = id ;
    this.name = name ;
}

xml configuration can be

<bean id = "test1" class = "相对项目的路径">
    <!--index为参数的位置,value为要注入的值-->
    <!--当参数为对象的时候,使用为ref = "对象的id"-->
    <constructor-arg index = "0" value = "xx"/>
    <constructor-arg index = "1" value = "yy"/>
</bean>

  Using constructor injection, the implementation is very simple, but the disadvantage is that it is very troublesome for the case of many parameters. At this time, setter injection should be considered.

setter injection

Setter injection is the most mainstream way of injection in Spring, which is flexible and highly readable.

xml configuration can be

<bean id = "test1" class = "相对项目的路径">
    <!--name为成员变量的名字,value为要注入的值-->
    <!--当参数为对象的时候,使用为ref = "对象的id"-->
    <property name = "id" value = "xx"/>
    <property name = "name" value = "yy"/>
</bean>

interface injection

There are two types of interface injection, one is to external resources, such as

<bean id="dataSource1" class="jdbc连接类">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost:3306/test" />
    <property name="username" value="root" />
    <property name="password" value="***" />
</bean>

For custom interface implementation

public interface A{
}

public class B impliment A{
    String id;
} 

For the custom interface A, inject it into the object B

<bean id = "aInterface" calss = "**/A"/>
<bean id = "b" class = "**/B">
     <property name="aInterface">
        <ref local="aInterface"/>
    </property>  
</bean>

In this way, the configuration injection can obtain the instance through reflection in the IOC container.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325749620&siteId=291194637