Spring 使用构造器装载属性

来源:互联网 发布:电视mac是什么意思啊 编辑:程序博客网 时间:2024/04/29 07:55

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方法

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

4.单元测试
/** * 构造器注入测试 */@Testpublic 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.


0 0
原创粉丝点击