Spring DI的3种方式

前面讲解IOC和DI入门的时候,对表现层依赖的service对象,使用了setter方法进行注入,这里对依赖注入的3中方式进行深入分析。

依赖注入的3中方式:

1、使用构造器注入

2、使用setter方法注入

3、使用接口注入

________________________________________________________________________________________________________

构造器注入

Car类:

public class Car {
	private String name;
	private int price;
	
	public Car(String name, int price) {
		this.name = name;
		this.price = price;
	}
	
	@Override
	public String toString() {
		return "Car [Name: " + name+ ", Price: "+ price + "]";
	}
}

applicationContext.xml

<bean id="car" class="cn.itcast.spring.e_di.Car">
	 <constructor-arg index="0" type="java.lang.String" value="宝马"></constructor-arg>
	 <constructor-arg index="1" type="int" value="10000"></constructor-arg>
</bean>

Test:

@Test
public void test(){
	ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
	Car car = (Car) applicationContext.getBean("car");
	System.out.println(car);
}

输出:

构造器注入需在bean标签中,设置<constructor-arg>标签,<constructor-arg>标签有以下几个属性:

    index 代表参数顺序 ,第一个参数 0
    type 代表参数类型
    name 代表参数的名称
    value 注入参数的值
    ref  引用另一个bean元素的id
   一般用index和type区分不同的构造器。

________________________________________________________________________________________________________

setter方法注入

Employee类:

public class Employee {
	private long id;
	private String name;
	
	public void setId(long id) {
		this.id = id;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	@Override
	public String toString() {
		return "Employee [id: " + id + ", name: "+name + "]";
	}

}

applicationContext.xml:

<bean id="employee" class="cn.itcast.spring.e_di.Employee">
	   <property name="id" value="1111"></property>
	   <property name="name" value="啊哈"></property>
</bean>

Test

@Test
public void test1(){
	ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
	Employee employee = (Employee) applicationContext.getBean("employee");
	System.out.println(employee);
}

输出:


<property>标签为setter方法注入方法提供实现,<property>标签的属性有:

   name 属性名称 (由setter方法获得)
   value 注入参数的值
   ref 引用另一个Bean元素的id

Spring配置文件支持构造参数属性注入 setter方法属性注入


  

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值