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
- Spring 使用构造器装载属性
- Spring(六)使用构造器装配属性
- Spring学习笔记05--使用构造器装配属性
- 使用构造器装配属性
- Spring bean属性注入(构造器)
- spring属性和构造器注入
- Spring 属性注入和构造器注入
- JAVA使用类装载器装载配置文件
- spring使用手动装载依赖的bean
- spring实例化bean以及构造器装配属性
- (二)spring的注入---配置构造器属性注入
- Spring属性注入和构造器注入、工厂方法注入
- spring的属性注入和构造器注入
- spring 使用构造器方式依赖注入
- Android 装载器---在应用程序中使用装载器
- Android 装载器---在应用程序中使用装载器
- Android 装载器---在应用程序中使用装载器
- 基础Java类使用类装载器实现装载配置文件
- 图 相关题目Ⅱ
- jdom学习:读取xml文件
- 第一篇,IT道路的开始
- KMP练习——KMP模式匹配 一(串)
- java获得执行jar的运行路径
- Spring 使用构造器装载属性
- 海量数据处理之Tire树(字典树)
- std::map的insert和下标[]访问
- ibatis缓存select字段
- 转载自rhino的Java enum的用法详解
- Android solve设备(手机)旋转过程中出现程序中断问题
- [分享] 安卓手机ROM和RAM的区别
- 2015-8-18数据结构-分冶-整数划分问题
- 安装过程中出现PKG_CONFIG_PATH的问题解决方法