Spring学习笔记之方法注入

时间:2022-05-09 22:02:22

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>