Several ways of Spring dependency injection

1. Constructor injection

<bean name="product1" class="com.*.*.Product">

    <constructor-arg index="0" value="name"/>

    <constructor-arg index="1" value="9.95"/>

</bean>

The corresponding constructor is

public Product(String name, float price){...}

The index parameter must correspond to the constructor parameter, base 0.


2. Default parameterless constructor injection

<bean name="product2" class="com.*.*.Product"/>

Compared with the first type, there is no constructor-arg tag, so it is a default no-argument constructor. The class must have a default no-argument constructor. If the constructor is overloaded, the displayed default constructor must be added.


3.setter method injection

<bean name="user" class="com.*.*.User">

    <property name="product1" ref="product1">

    <property name="product2" ref="product2">

</bean>

ref is an instance, which is injected through setter. It should be noted that the class getter and setter used must be perfect. The configuration position of the referenced object is irrelevant and can be defined after the referenced object.


4. Factory Method Injection

<bean name="product" class="com.*.*.Product"

    factory-method="getInstance"/>

All methods can add the destroy-method tag to specify the destruction method

<bean name="product" class="com.*.*.Product"

    factory-method="getInstance"

    destory-method="shutdown"/>



Guess you like

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