在spring中,依赖注入有多种种方式,今天,我们学习一下最常用的几种方式用法,分别是:
1.构造函数注入,官网例子如下图:
总结:使用constructor-arg标签完成注入,
type用于指定要注入数据的数据类型,与构造函数的参数类型相对应。
index指定构造函数中参数的索引位置,从0开始。
name指定构造函数中的参数名称。
ref指定配置在spring的IOC核心容器中的bean。
value提供基本数据类型和String类型的数据。
举例:
package cn.com.gjw.service.impl;
import cn.com.gjw.factory.BeanFactory;
import cn.com.gjw.service.AccountService;
import cn.com.gjw.dao.AccountDao;
import cn.com.gjw.dao.impl.AccountDaoImpl;
/*账户业务层实现类*/
public class AccountServiceImpl implements AccountService {
private String name;
private int age;
private AccountDao dao;
//通过构造方法注入
public AccountServiceImpl(String name, int age, AccountDao dao) {
this.name = name;
this.age = age;
this.dao = dao;
}
public void saveAccount() {
System.out.println(name+"---"+age+"---"+dao);
}
}
beans.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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- spring的IOC容器 -->
<bean id="accountService" class="cn.com.gjw.service.impl.AccountServiceImpl">
<!--type为String类型-->