Bean注入方式1:使用Setter方式装配属性(依赖注入)
注入依赖对象
基本类型对象注入:
<bean id="orderService" name="code"><bean id="persionDao" init-method="init" destroy-method="destory"> <property name="persionDao" ref="persionDao"> </property> </bean>
方式二(使用内部bean,但该bean不能被其他bean使用)
<bean id="orderService" name="code">package cn.com.xinli.dao; public interface PersionDao { public abstract void add(); } (2) 接口实现PersionDaoBean package cn.com.xinli.dao.impl; import org.apache.log4j.Logger; import cn.com.xinli.dao.PersionDao; public class PersionDaoBean implements PersionDao { Logger log=Logger.getLogger(PersionDaoBean.class); /* (non-Javadoc) * @see cn.com.xinli.dao.impl.PersionDao#add() */ public void add() { log.info("执行了PersionDaoBean中的add()方法"); } }?
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; 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() { this.persionDao.add(); } public void destory() { log.info("释放资源"); } }?
<bean id="persionDao" init-method="init" destroy-method="destory"> <property name="persionDao" ref="persionDao"></property> </bean>?
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); PersionSevice ps=(PersionSevice)ctx.getBean("persionServiceBean"); ps.save();?
/** * 为属性注入值 */ private void injectObject() { for(BeanDefinition beanDefinition : beanDefines){ Object bean = sigletons.get(beanDefinition.getId()); if(bean!=null) { try { //得到bean对象所有的属性声明,返回的是一个数组 PropertyDescriptor[] ps = Introspector.getBeanInfo(bean.getClass()).getPropertyDescriptors(); for(PropertyDefinition propertyDefinition : beanDefinition.getPropertys()) { for(PropertyDescriptor properdesc : ps) { //如果xml中读取的属性名字是bean对象属性的名字 if(propertyDefinition.getName().equals(properdesc.getName())) { //setter方法是写方法 Method setter = properdesc.getWriteMethod(); //获取属性的setter方法 ,如果方法是private需要调用 if(setter!=null) { Object value = sigletons.get(propertyDefinition.getRef()); setter.setAccessible(true); setter.invoke(bean, value);//把引用对象注入到属性 } break; } } } } catch (Exception e) { } } } }?
ItcastClassPathXMLApplicationContext ctx = new ItcastClassPathXMLApplicationContext("beans.xml"); PersionSevice ps=(PersionSevice)ctx.getBean("persionServiceBean"); ps.save();