当我们需要在一个单例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