首页 > 编程语言 > 详细

Spring学习笔记之方法注入

时间:2014-12-16 11:19:08      阅读:277      评论:0      收藏:0      [点我收藏+]

public  abstract class ReplacedBean {
protected static final Log log = LogFactory.getLog(ReplacedBean.class);
  
    public void process() {
      
        AnotherBean anotherBean = createAnotheBean();
        anotherBean.doSth();
      
    }
    protected abstract AnotherBean createAnotheBean();
  
}

<bean id="AnotherBean" class="com.test.spring.di.mtddi.AnotherBean"  scope="prototype"/>

<bean id="ReplacedBean" class="com.test.spring.di.mtddi.ReplacedBean" >
        <lookup-method name="createAnotheBean" bean="AnotherBean"/>
    </bean>

 

 

Bean A实现 ApplicationContextAware, Spring初始化的时候会将 ApplicationContext 传给Bean A,Bean A通过getBean("BeanB")方法每次得到Bean B.("BeanB"最好不要hardcode,通过property传入)例:

public class ContextAwareBean implements ApplicationContextAware {
    protected static final Log log = LogFactory.getLog(AnotherBean.class);
    private String anotherBeanName;
    private ApplicationContext applicationContext;
  
    public String getAnotherBeanName() {
        return anotherBeanName;
    }
    public void setAnotherBeanName(String anotherBeanName) {
        this.anotherBeanName = anotherBeanName;
    }
    public void process() {
        log.info("process applicationContext " + applicationContext);
        AnotherBean anotherBean = createAnotheBean();
        anotherBean.doSth();
      
    }
    protected AnotherBean createAnotheBean() {
  
    return this.applicationContext.getBean(anotherBeanName, AnotherBean.class);
    }
    public void setApplicationContext(ApplicationContext applicationContext){
        log.info("setApplicationContext " + applicationContext);
        this.applicationContext = applicationContext;
    }
}
&nbsp;public class AnotherBean {
    protected static final Log log = LogFactory.getLog(AnotherBean.class);
    public String doSth(){
        log.info("AnotherBean.doSth");
        return "do something";
    }
}

<bean id="AnotherBean" class="com.test.spring.di.mtddi.AnotherBean"  scope="prototype"/>
  
    <bean id="ContextAwareBean" class="com.test.spring.di.mtddi.ContextAwareBean" >
        <property name="anotherBeanName" value="AnotherBean"/>
    </bean>

Spring学习笔记之方法注入

原文:http://www.cnblogs.com/shunliu-java/p/4166536.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!