Spring构造函数注入

Spring依赖注入

一、Spring能注入的三类数据:

(1)基本类型和String
(2)其他Bean类型(在配置文件中或者注解配置过的Bean)
(3)复杂类型/集合类型

二、注入的三种方式:

(1)构造函数注入
(2)set方法注入
(3)注解注入


2.1构造函数注入:

经常变化的数据,并不适用于注入的方式

实现过程如下:

service层模拟构造函数导入数据:

public class TestServiceImpl implements ITestService {

    //只是模拟一个数据类型
    private String name;
    private int age;
    private Date birthday;

    /**
     * 有参构造函数注入
     * @param name
     * @param age
     * @param birthday
     */
    public TestServiceImpl(String name, int age, Date birthday){
        this.name = name;
        this.age = age;
        this.birthday = birthday;
    }

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

文件放置结构
文件的放置结构

接口中并没有任何东西


# applicationContext.xml的配置:
<constructor-arg>写在<bean></bean>内部
属性:
	type:指定注入的数据类型
	index:构造函数中参数的索引位置,从0开始
	 例:
	     public TestServiceImpl(String name, int age, Date birthday)
	                           取值:    0         1         2
	name:构造函数中指定名称的参数赋值**(常用)**
	例:
	     public TestServiceImpl(String name, int age, Date birthday)
	                           取值:  name      age       birthday
	
	---------------以上都是指定构造器中哪个参数赋值--------------------
	value:注入的值,用于注入**基本类型和String**
	ref:引用关联的bean对象,其他bean类型
		spring的Ioc核心容器中出现过的bean对象
以上是constructor-arg标签的基本使用

下面是applicationContext.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">
	<!--实现构造函数注入-->
	<!--id是引用这个bean的id,class是这个实现类的全限定类名-->
    <bean id="testService" class="com.demo.service.impl.TestServiceImpl">
        <constructor-arg name="name" value="test"></constructor-arg>
        <constructor-arg name="age" value="18"></constructor-arg>
        
        <!--birthday是一个其他bean类型数据,需要引用其他的<bean>id-->
        <constructor-arg name="birthday" ref="now"></constructor-arg>
        
    </bean>
    <!-- 配置一个日期对象,给上面的birthday引用-->
    <bean id="now" class="java.util.Date"></bean>
</beans>

view模拟表现层调用业务层:

public class Client {
    public static void main(String[] args) {
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");

        //传入配置文件中id,和接口的字节码进行强转,得到需要的对象
        ITestService ts = ac.getBean("testService",ITestService.class);
        System.out.println(ts);
    }
}

打印结果是applicationContext.xml配置文件的配置内容
在这里插入图片描述
优势:
在获取bean对象时,必须注入数据,否则对象无法创建成功。
弊端:
改变了bean对象原来的无参实例化方式,使我们在创建对象时,如果用不到这些数据,也必须提供。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值