Spring之Method Injection

对于Spring的多数用户而言,主要的Bean存在形式都是单例,当一个单例需要结合另一个单例协作或者一个非单例与另一个非单例协作时,典型的做法是通过属性的形式注入,但是当两个Bean的声明周期不同时候这会存在一个问题。例如单例A依赖一个非单例B,而对外提供的服务是通过A暴露的,这样的话每一次调用A的方法时候都不会更新实例B,这将会导致问题(因为A的属性只在初始化时候被设置一次,之后不再被设置)。对于这个问题有如下解决方案:

1:不再使用以来注入,而是实现BeanFactoryAware接口之后每一次通过getBean的方法获取一个新的实例B,但是这通常不是一个理想的解决方案,因为bean代码耦合到Spring中。

2:Method Injection是BeanFactory的一个高级特性,以一种优雅的方式解决此问题。

public abstract class UserService {

    public abstract WalletService createWalletService() ;
    public UserService() {
        System.out.println("UserService 正在实例化!");
    }

    public void login(String userName, String passWord) {
        createWalletService().run();
        System.out.println(userName + "正在登陆!");
    }
}

  

public  class WalletService {
    public WalletService(){
        System.out.println("CarService");
    }
    public void run() {
        System.out.println("this = " + this);
    }
}

walletService是一个非单例bean,每一次用户调用时候都必须获取一个新的walletService进行请求,这种需求配置如下:

    <bean id="walletService" class="com.daxin.service.WalletService" singleton="false"/>
    <bean id="userService" class="com.daxin.service.UserService">
        <lookup-method name="createWalletService" bean="walletService"></lookup-method>
     </bean>  

测试代码:

    public static void main(String[] args) throws CloneNotSupportedException {
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
        for (int i = 0; i < 5; i++) {
            UserService userService = (UserService) ctx.getBean("userService");
            userService.login("daxin", "root");
        }
        ctx.close();
    }

  

测试输出:

daxin正在登陆!
CarService
this = com.daxin.service.WalletService@40e6dfe1
daxin正在登陆!
CarService
this = com.daxin.service.WalletService@1b083826
daxin正在登陆!
CarService
this = com.daxin.service.WalletService@105fece7
daxin正在登陆!
CarService
this = com.daxin.service.WalletService@3ec300f1
daxin正在登陆!

  

猜你喜欢

转载自www.cnblogs.com/leodaxin/p/9383863.html