使用构造器注入:
以前我们都是使用setter方法给属性注入值的,现在我们来看看另外一种注入方法:构造器注入
步骤:
(1)改写 PersionServiceBean.java ,为注入的属性加上构造方法
package cn.com.xinli.service.impl;
import org.apache.log4j.Logger;
import cn.com.xinli.dao.PersionDao;
import cn.com.xinli.service.PersionSevice;
public class PersionServiceBean implements PersionSevice
{
Logger log=Logger.getLogger(PersionServiceBean.class);
private PersionDao persionDao;
private String name;
public PersionServiceBean(PersionDao persionDao, String name) {
this.persionDao = persionDao;
this.name = name;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public PersionDao getPersionDao()
{
return persionDao;
}
public void setPersionDao(PersionDao persionDao)
{
this.persionDao = persionDao;
}
public void init()
{
log.info("初始化资源");
}
public PersionServiceBean()
{
log.info("我被实例化了");
}
public void save()
{
log.info("name:"+name);
this.persionDao.add();
}
public void destory()
{
log.info("释放资源");
}
}
(2) 配置beans.xml,其中配置了一个依赖属性和一个基本的String类型
<bean id="persionServiceBean" class="cn.com.xinli.service.impl.PersionServiceBean" init-method="init" destroy-method="destory"> <constructor-arg index="0" type="cn.com.xinli.dao.PersionDao" ref="persionDao"></constructor-arg> <constructor-arg index="1" value="huxl"></constructor-arg> </bean>
(3) 测试:
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
PersionSevice ps=(PersionSevice)ctx.getBean("persionServiceBean");
ps.save();
结果:
INFO (PersionServiceBean.java:37) - 初始化资源
INFO (PersionServiceBean.java:46) - name:huxl
INFO (PersionDaoBean.java:15) - 执行了PersionDaoBean中的add()方法
目前学习到了两种注入方式:
1.setter方式
2.构造起方式