使用构造器注入
<?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="cn.itcast.dao.impl.PersonDaoBean"></bean>
<bean id="personService" class="cn.itcast.service.impl.PersonServiceBean">
<!-- 使用构造器参数注入 -->
<constructor-arg index="0" type="cn.itcast.dao.PersonDao" ref="personDao"></constructor-arg>
<constructor-arg index="1" value="传智博客"></constructor-arg>
</bean>
</beans>
---------------------------------------------------------------------------------------------------
public class PersonServiceBean implements PersonService {
private PersonDao personDao;
private String name;
public PersonServiceBean(PersonDao personDao, String name) {
this.personDao = personDao;
this.name = name;
}
@Override
public void save(){
System.out.println(name);
personDao.add();
}
}
<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="cn.itcast.dao.impl.PersonDaoBean"></bean>
<bean id="personService" class="cn.itcast.service.impl.PersonServiceBean">
<!-- 使用构造器参数注入 -->
<constructor-arg index="0" type="cn.itcast.dao.PersonDao" ref="personDao"></constructor-arg>
<constructor-arg index="1" value="传智博客"></constructor-arg>
</bean>
</beans>
---------------------------------------------------------------------------------------------------
public class PersonServiceBean implements PersonService {
private PersonDao personDao;
private String name;
public PersonServiceBean(PersonDao personDao, String name) {
this.personDao = personDao;
this.name = name;
}
@Override
public void save(){
System.out.println(name);
personDao.add();
}
}