【Spring】依赖注入DI

依赖注入

概念

依赖注入:Dependency Injection。它是spring框架核心ioc的具体实现。

程序在编写时,通过控制反转,把对象的创建交给了 spring,但是代码中不可能出现没有依赖的情况。ioc 解耦只是降低他们的依赖关系,但不会消除。

例如:我们的业务层仍会调用持久层的方法。 那这种业务层和持久层的依赖关系,在使用 spring 之后,就让 spring 来维护了。
简单的说,就是坐等框架把持久层对象传入业务层,而不用我们自己去。

注入方式

构造函数注入

使用类中的构造函数,给成员变量赋值。注意,赋值的操作不是我们自己做的,而是通过配置 的方式,让 spring 框架来为我们注入。

public class AccountServiceImpl implements IAccountService {
private String name; 
    private Integer age; 
    private Date birthday;
public AccountServiceImpl(String name, Integer age, Date birthday) { this.name = name;
	this.age = age;
	this.birthday = birthday; }
	@Override
	public void saveAccount() { System.out.println(name+","+age+","+birthday);
} }


使用构造函数的方式,给 service 中的属性传值。
要求:类中需要提供一个对应参数列表的构造函数。 涉及的标签:
constructor-arg
属性: 
//赋值对象
index:指定参数在构造函数参数列表的索引位置 
type:指定参数在构造函数中的数据类型
name:指定参数在构造函数中的名称用这个找给谁赋值 
//赋值内容
value:它能赋的值是基本数据类型和 String 类型
ref:它能赋的值是其他 bean 类型,也就是说,必须得是在配置文件中配置过的 bean
    
<bean id="accountService" class="com.xxx.service.impl.AccountServiceImpl">
	<constructor-arg name="name" value="张三"></constructor-arg> 
    <constructor-arg name="age" value="18"></constructor-arg>
	<constructor-arg name="birthday" ref="now"></constructor-arg> 
</bean>
<bean id="now" class="java.util.Date"></bean>

set方法注入

在类中提供需要注入成员的 set 方法。

public class AccountServiceImpl implements IAccountService {
	private String name;
	private Integer age; 
    private Date birthday;
    
	public void setName(String name) { 
        this.name = name;
	}
	public void setAge(Integer age) {
		this.age = age; }
	public void setBirthday(Date birthday) { 
    	this.birthday = birthday;
	}
	@Override
	public void saveAccount() { 
        System.out.println(name+","+age+","+birthday);
} }

通过配置文件给 bean 中的属性传值:使用 set 方法的方式 涉及的标签:
property
属性:
name:找的是类中 set 方法后面的部分 
ref:给属性赋值是其他 bean 类型的 
value:给属性赋值是基本数据类型和 string 类型的
实际开发中,此种方式用的较多。
    
    
<bean id="accountService" class="com.xxx.service.impl.AccountServiceImpl">
	<property name="name" value="test"></property> 
    <property name="age" value="21"></property> 
    <property name="birthday" ref="now"></property>
</bean>
<bean id="now" class="java.util.Date"></bean>
发布了18 篇原创文章 · 获赞 0 · 访问量 271

猜你喜欢

转载自blog.csdn.net/shijyuan/article/details/104751053