我创建了下面的类和接口但是没有调用原型bean构造函数。我正在使用@Lookup来创建原型范围的bean。
public interface IProtoTypeBean {}
@Component
@Scope(value = "prototype")
public class ProtoTypeBean implements IProtoTypeBean {
public ProtoTypeBean() {
super();
System.out.println("ProtoTypeBean");
}
}
@Component
public class SingleTonBean {
IProtoTypeBean protoTypeBean = getProtoTypeBean();
@Lookup
public ProtoTypeBean getProtoTypeBean(){
return null;
}
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(SingleTonBean.class);
SingleTonBean s1 = ctx.getBean(SingleTonBean.class);
IProtoTypeBean p1 = s1.protoTypeBean;
SingleTonBean s2 = ctx.getBean(SingleTonBean.class);
IProtoTypeBean p2 = s2.protoTypeBean;
System.out.println("singelton beans " + (s1 == s2));
// if ProtoTypeBean constructor getting called 2 times means diff objects are getting created
}
}
答案 0 :(得分:0)
将您的代码更改为以下步骤
@Component("protoBean")
@Scope(value = "prototype") public class ProtoTypeBean implements IProtoTypeBean {
和
@Lookup(value="protoBean")
public abstract ProtoTypeBean getProtoTypeBean();
答案 1 :(得分:0)
我建议使用原型提供程序。
添加maven依赖
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
然后提及由Spring管理的两个类
ApplicationContext ctx = new AnnotationConfigApplicationContext(SingleTonBean.class, ProtoTypeBean.class);
这是提供者用法
@Component
public class SingleTonBean {
@Autowired
private Provider<IProtoTypeBean> protoTypeBeanProvider;
public IProtoTypeBean getProtoTypeBean() {
return protoTypeBeanProvider.get();
}
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(SingleTonBean.class, ProtoTypeBean.class);
SingleTonBean s1 = ctx.getBean(SingleTonBean.class);
IProtoTypeBean p1 = s1.getProtoTypeBean();
SingleTonBean s2 = ctx.getBean(SingleTonBean.class);
IProtoTypeBean p2 = s2.getProtoTypeBean();
System.out.println("singleton beans " + (s1 == s2));
System.out.println("prototype beans " + (p1 == p2));
}
}