码迷,mamicode.com
首页 > 编程语言 > 详细

Spring学习笔记之方法注入

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

标签:style   ar   io   color   os   sp   on   log   bs   

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学习笔记之方法注入

标签:style   ar   io   color   os   sp   on   log   bs   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!