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
