Spring - 运行时获取bean(ApplicationContextAware接口)

默认情况下,我们的bean都是单例模式(即从容器初始化到销毁只保持一个实例)。当一个bean需要引用另外一个bean,我们往往会通过bean属性的方式通过依赖注入来引用另外一个bean。那么问题就来了,假设一个单例模式的bean A需要引用一个非单例模式的bean B,并且bean A的所有方法都用到了bean B,我们希望每次都拿到最新的bean B。如果用之前的依赖注入模式,bean A只能再实例化的时候通过setter方式或者构造函数方式拿到一次bean B,所以bean A不能在每次需要bean B的时候保证都拿到最新的bean B。

 

牛逼的Spring又给我们提供了解决方案,那就是ApplicationContextAware接口。通过ApplicationContextAware我们可以拿到容器(applicationContext对象),通过容器的getBean方法我们就可以拿到最新的bean B了。示例代码如下:

//a class that uses a stateful Command-style class to perform some processing
package fiona.apple;

//Spring-API imports
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class CommandManager implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    public Object process(Map commandState) {
        // grab a new instance of the appropriate Command
        Command command = createCommand();
        // set the state on the (hopefully brand new) Command instance
        command.setState(commandState);
        return command.execute();
    }

    protected Command createCommand() {
        // notice the Spring API dependency!
        return this.applicationContext.getBean("command", Command.class);
    }

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}

这种实现方式也有一定的缺点,就是与Spring耦合了,那么就背离了IoC原则(完全由容器管理bean)。

然后。。。spring又给我们提供了一个可以继续使用IoC又能实现上面场景的方法,那就是<lookup-method>标签。

转载于:https://www.cnblogs.com/ViviChan/p/4981635.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值