Spring——單例Bean中使用多例Bean


通常bean都是單例的,如果一個bean需要依賴另一個bean時,被依賴的bean始終為單例的

讓自定義bean獲得applicationContext的能力

org.springframework.context.ApplicationContextAware

public interface ApplicationContextAware extends Aware {

	void setApplicationContext(ApplicationContext applicationContext) throws BeansException;

}

繼承ApplicationContextAware

public static class b implements ApplicationContextAware {
        a a1;

        public void say(){
            a1 = this.getA1();
            System.out.println(a1);
            System.out.println(this);
        }

        public a getA1() {
            return context.getBean(a.class);

        }
		//定義一個變量存放context
        private ApplicationContext context;
        //設置context的值
        @Override
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            this.context = applicationContext;
        }
    }

lookup-method實現

以上的方法對spring的api耦合過高,通過lookup-method方式解決

在bean中配置

通過對方法攔截。name為攔截方法名,bean為替換返回值的bean的id

	<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="a" class="com.shimeath.test.demo7.test.a" scope="prototype"/>
    <bean id="b" class="com.shimeath.test.demo7.test.b">
        <lookup-method name="getA1" bean="a"/>
    </bean>

</beans>

replaced-method方法替換

通過對bean中的某一方法進行攔截,將請求轉發到替換者處理

  1. 定義替換者
public static class Repl implements ApplicationContextAware, MethodReplacer{
        @Override
        public Object reimplement(Object obj, Method method, Object[] args) throws Throwable {
            return this.context.getBean(a.class);
        }

        ApplicationContext context;

        @Override
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            this.context = applicationContext;
        }
    }
  1. 定義bean
    <bean id="repl" class="com.shimeath.test.demo7.test.Repl"/>
  1. 替換方法
    <bean id="b" class="com.shimeath.test.demo7.test.b">
        <replaced-method name="getA1" replacer="repl"/>
    </bean>

完整xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="repl" class="com.javacode2018.lesson001.demo7.test.Repl"/>
    <bean id="a" class="com.javacode2018.lesson001.demo7.test.a" scope="prototype"/>
    <bean id="b" class="com.javacode2018.lesson001.demo7.test.b">
        <replaced-method name="getA1" replacer="repl"/>
    </bean>

</beans>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM