Spring_09_DI之构造器注入

前文:Spring_08_DI之Setter注入

DI之构造器注入

通过构造器的参数进行注入,Spring提供三种方式来匹配参数。

在<bean>的<constructor-arg>中,有下列三个属性。

name:通过参数名。

type:通过参数类型。

index:通过参数位置。(0开始)

即使在配置文件中,所配置的参数标签和构造器参数位置不一致,

Spring也能自动选择最匹配的构造方法。

但是在配置文件中所配置的参数,必须存在对应的构造方法以供注入,

即:用于注入的构造方法中的参数,在配置文件中必须进行配置。

其余的配置细节与Setter类似。

· 配置演示

BeanObject

@ToString
public class BeanObject implements IBeanObject {
    /* 简单值 */
    private long sn;
    private String name;

    /* 依赖的bean对象 */
    private IOtherBean other;

    /* 集合 */
    private List list;

    /* Properties对象*/
    private Properties properties;

    public BeanObject(long sn, String name, IOtherBean other, List list,
                      Properties properties) {
        this.sn = sn;
        this.name = name;
        this.other = other;
        this.list = list;
        this.properties = properties;
    }

    public BeanObject(){
        System.out.println("new BeanObject");
    }
}

配置文件


    <bean id="otherBean" name="other" class="com.hanaii.di.constructor.OtherBean"/>
    <bean id="beanObject" class="com.hanaii.di.constructor.BeanObject">
        <!-- 使用参数名字匹配 -->
        <constructor-arg name="name" value="hanaii"/>
          
        <!-- 使用参数类型匹配 -->
        <constructor-arg type="long" value="1"/>
        
        <!-- 使用参数索引匹配 -- >
        <constructor-arg index="2" ref="otherBean"/>

        <!-- 具体的配置和setter注入类似 -->
         <constructor-arg name="properties">
            <props >
                <prop key="system_langunge">简体中文</prop>
            </props>
        </constructor-arg>  
    
         <constructor-arg name="list" >
            <list>
                <value>1</value>
            </list>
        </constructor-arg>
    </bean>
</beans>

配置文件中参数顺序和构造方法不一致,也没关系,Spring会自动匹配。

测试代码

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class ConstructorTest {

    @Autowired
    ApplicationContext ctx;

    @Test
    public void test1(){
        BeanObject obj = ctx.getBean("beanObject", BeanObject.class);
        System.out.println(obj);
    }
}

测试结果

BeanObject(sn=1, name=hanaii, 
other=com.hanaii.di.constructor.OtherBean@69b794e2, 
list=[1], properties={system_langunge=简体中文})

猜你喜欢

转载自blog.csdn.net/hanaii/article/details/82527917