Spring学习笔记(三)

1、构造器注入

这种方式的注入是指带有参数的构造函数注入。

2、实例

(1)PersonDao.java

public interface PersonDao {

	public void add();
}

(2)PersonDaoBean.java

public class PersonDaoBean implements PersonDao {

	public void add() {
		
		System.out.println("PersonDaoBean add");
	}
}

(3)PersonService.java

public interface PersonService {

	public void save();
}

(4)PersonServiceBean.java

public class PersonServiceBean implements PersonService {

	private PersonDao personDao;
	private String name;
	
	public PersonServiceBean(PersonDao personDao, String name) {
		
		this.personDao = personDao;
		this.name = name;
	}

	public void save() {
		
		System.out.println(name);
		personDao.add();
	}
}

(5)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
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
           
	<bean id="personDao" class="com.spring.dao.impl.PersonDaoBean"></bean>

	<bean id="personService1" class="com.spring.service.impl.PersonServiceBean">
		<!-- 
			依赖注入:使用构造器注入
		-->
       	<constructor-arg index="0" type="com.spring.dao.PersonDao" ref="personDao"/>
       	<constructor-arg index="1" value="Tom"/>  	
	</bean>
	
	<bean id="personService2" class="com.spring.service.impl.PersonServiceBean">
       	<constructor-arg index="0" type="com.spring.dao.PersonDao">
       		<bean class="com.spring.dao.impl.PersonDaoBean"/>
       	</constructor-arg>
       	<constructor-arg index="1" value="Jerry"/>  	
	</bean>
</beans>

(6)Test.java

public class Test {

	@org.junit.Test
	public void test1() {
		
		ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
		PersonService personService = (PersonService)ctx.getBean("personService1");
		personService.save();
	}

	@org.junit.Test
	public void test2() {
		
		ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
		PersonService personService = (PersonService)ctx.getBean("personService2");
		personService.save();
	}
}

3、结果

test1()运行结果:

Tom
PersonDaoBean add

test2()运行结果:

Jerry
PersonDaoBean add

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值