1.在javaBean中将属性通过构造器传入:
private PersonDao personDao;
private String name;
public PersonServiceBean(PersonDao personDao, String name) {
this.personDao = personDao;
this.name = name;
}
2.在bean.xml文件中配置,从而注入值
<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 index="1" value="test by lic."></constructor-arg>
<!--
<property name="personDao" ref="personDao">
</property>
<property name="name" value="itcast"></property>
<property name="id" value="32"></property>
-->
</bean>
index="0"表示构造器中的第一个参数,如果是引用的话使用ref,如果是基本类型直接使用value来设值。
3.重写dao的save方法
@Override
public void save() {
personDao.add();
System.out.println(name);
}
4.单元测试
/**
* 构造器注入测试
*/
@Test
public void instanceSpring6() {
AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
PersonService personService = (PersonService)ctx.getBean("personService");
personService.save();
}
5.测试结果
九月 01, 2015 9:39:26 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@14d0ba03: display name [org.springframework.context.support.ClassPathXmlApplicationContext@14d0ba03]; startup date [Tue Sep 01 21:39:26 CST 2015]; root of context hierarchy
九月 01, 2015 9:39:26 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [beans.xml]
九月 01, 2015 9:39:27 下午 org.springframework.context.support.AbstractApplicationContext obtainFreshBeanFactory
信息: Bean factory for application context [org.springframework.context.support.ClassPathXmlApplicationContext@14d0ba03]: org.springframework.beans.factory.support.DefaultListableBeanFactory@547e045
九月 01, 2015 9:39:27 下午 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@547e045: defining beans [personDao,personService]; root of factory hierarchy
执行PersonDaoBean中的add()方法.
test by lic.