spring的@Lookup注解实现单例中调用多例

当我们需要在一个单例bean1中引入另外一个bean2,但是希望被调用的这个bean2是非单例的时候可以使用lookup注解来实现

首先给出错误的写法:

@Component
@Scope("prototype")
public class PrototypeBean {
    public void say() {
        System.out.println("say something...");
    }
}
 
@Component
public  class SingletonBean  {
 
    @Autowired
    private PrototypeBean bean;
 
    public void print() {
        System.out.println("Bean SingletonBean's HashCode " + bean.hashCode());
    }
 
}

虽然我们生命了PrototypeBean是原型模式,但是因为是在一个单例bean里注入,那么这个bean只会被注入一次,多次获取SingletonBean并调用print()方法结果是相同的。

 

一个方法就是我们让SingletonBean实现ApplicationContextAware接口,然后每次都通过context获取bean,这样确实是可以的,但是我们有更好的方案。

 

使用lookup注解,添加一个返回值为这个bean的无参方法,并在方法上添加@Lookup注解,就实现了该功能.

对于@Lookup修饰的方法,有相对应的标准

<public|protected> [abstract] <return-type> theMethodName(no-arguments);
 
public|protected 要求方法必须是可以被子类重写和调用的
abstract 可选,如果是抽象方法,CGLIB的动态代理类就会实现这个方法,如果不是抽象方法,就会覆盖这个方法
return-type 是非单例的类型
no-arguments 不允许有参数
有两种写法:(注意:别忘了PrototypeBean中,务必一直都得有这个多例标签 —— @Scope("prototype"))

1、

@Component
public class SingletonBean {
 
    public void print() {
        PrototypeBean bean = methodInject();
        System.out.println("Bean SingletonBean's HashCode " + bean.hashCode());
    }
 
    @Lookup
    protected PrototypeBean methodInject() {
        return null;
    }
}

2、

@Component
public abstract class SingletonBean {
 
    public void print() {
        PrototypeBean bean = methodInject();
        System.out.println("Bean SingletonBean's HashCode " + bean.hashCode());
    }
 
    @Lookup
    protected abstract PrototypeBean methodInject();
}


参考:

https://segmentfault.com/a/1190000018961118?utm_source=tag-newest

https://www.jianshu.com/p/fc574881e3a2
--------------------- 

转载自:https://blog.csdn.net/dezhonger/article/details/95238732

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值