Spring的构造器注入(了解)

本文介绍了Spring框架中的构造器注入机制,强调了在XML配置文件中如何手动配置以向对象属性传递值。内容涵盖了构造器注入的要求,包括对象需有参数的构造函数,以及在XML中配置`constructor-arg`标签的细节。根据属性类型,注入方式分为简单数据类型使用`value`,复合数据类型使用`ref`,集合数据类型使用集合元素。总结指出构造器注入与setter注入的相似性,并要求在对象中对应所有要注入的属性构造函数。

构造器注入:利用构造函数为对象中的属性注入值,需要在xml配置文件中进行手动的配置.

要求:
对象中必须存在有参数的构造函数.xml中手动配置了哪些属性需要注入值,对象中必须存在对应的属性为参数的构造函数.

如何配置:
需要为对象中的每个属性配置一个"constructor-arg"标签:

<constructor-arg name="" />

其中name属性的值构造函数中形参的名字.如何给属性注入值时,需要先确定该属性的类型(与setter注入方式类似)

对象中的属性分为以下三种类型,不同的类型使用不同的注入方式
1):简单数据类型(八大基本类型,String,BigDecimal,Date等). 使用value.
2):复合数据类型. 使用ref.
3):集合数据类型. 使用集合的元素.

小结:
1.构造器的注入方式与setter注入方式类型,配置文件只是把setter注入方式中的"property"标签替换为"constructor-arg"标签.
2.使用构造器注入方式,在xml配置文件中配置了要为哪些属性注入值,在对象中必须存在对应的所有属性的构造函数.

代码:
App-context.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">




    <bean id="employee" class="text.spring._02_constructor.Employee">
        <constructor-arg name="name" value="jack"/>
        <constructor-arg name="age" value="18"/>
        <constructor-arg name="birthday" value="2019/01/01"/>
        <constructor-arg name="salary" value="1000.00"/>

        

    </bean>

</beans>

App.java:

package text.spring._02_constructor;


import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * Created by thinkpad on 2019/9/3.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class App {


    @Autowired
    private Employee employee;

    @Test
    public void testEmployee() throws Exception {
        System.out.println(employee);
    }
}

Employee.java:

package text.spring._02_constructor;

import java.math.BigDecimal;
import java.util.Date;

/**
 * Created by thinkpad on 2019/9/3.
 */
public class Employee {

    private String name;

    private Integer age;

    private Date birthday;

    private BigDecimal salary;


    public Employee(String name, Integer age, Date birthday, BigDecimal salary) {
        this.name = name;
        this.age = age;
        this.birthday = birthday;
        this.salary = salary;
    }


    public Employee() {
    }

    @Override
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", birthday=" + birthday +
                ", salary=" + salary +
                '}';
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值