Spring的DI(Ioc) - 利用构造器注入

时间:2023-03-08 16:06:02
Spring的DI(Ioc) - 利用构造器注入

1: 在给对象提供构造器

public class PersonServiceImpl implements PersonService {

	private PersonDao personDao;
private String name; public PersonServiceImpl(PersonDao personDao, String name) {
super();
this.personDao = personDao;
this.name = name;
} public void save() {
personDao.save();
System.out.println("name = " + name);
System.out.println("service : " + " save 方法");
} }

  

2: 配置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="personDaoImpl" class="cn.gbx.dao.PersonDaoImpl"></bean>
<bean id="personServiceImpl" class="cn.gbx.serviceimpl.PersonServiceImpl" >
<constructor-arg index="0" type="cn.gbx.daoimpl.PersonDao" ref="personDaoImpl">
</constructor-arg>
<constructor-arg index="1" value="Myname"></constructor-arg>
</bean>
</beans>

  

3: 测试即可。