spring依赖注入(二)之 构造注入

构造注入就是指在构造事例时,已经为其完成了依赖关系的初始化,因此在现实类中必须要有类的构造器才行,

这里我们构造了personserviceImpl的构造器:

public class PersonServiceImpl implements PersonService { private PersonDao personDao; private String name; public PersonServiceImpl(PersonDao personDao, String name) { this.personDao = personDao; this.name = name; } /* (non-Javadoc) * @see com.ncut.service.PersonService#save() */ public void save() { //System.out.println("这是personservice的实现类save()"); personDao.add(); System.out.println(name); } }

其他的地方不改变就是在applicationContext.xml的配置文件中进行简单的配置:

<bean id="personService" class="com.ncut.service.PersonServiceImpl"> <constructor-arg index="0" type="com.ncut.dao.PersonDao" ref="personDao"></constructor-arg> <constructor-arg index="1" value="北方工业大学"></constructor-arg> </bean> <bean id="personDao" class="com.ncut.dao.PersonDaoImpl"></bean>


我们看到了<constructor-arg>这样的标签就知道这就是为构造器准备的,其中index索引是指构造器中的函数变量位置,ref则是依赖对象spring会自动找到配置文件中的对像名。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值