通常在Spring Context中,如果在单例bean中注入原型bean,则父类的属性将覆盖原型bean范围。但是,如果在原型bean范围中注入单例范围bean,将会发生什么。 仍然使用内部bean的get bean将返回内部bean的新实例?
答案 0 :(得分:0)
不,prototype
bean的所有实例都将共享singleton
bean的相同实例
例:
@Service
public class SingletonBean {
private int id;
private static int static_id = 0;
public SingletonBean() {
id = static_id++;
}
@Override
public String toString() {
return "SingletonBean [id=" + id + "]";
}
}
@Service
public class SingletonBean {
private int id;
private static int static_id = 0;
public SingletonBean() {
id = static_id++;
}
@Override
public String toString() {
return "SingletonBean [id=" + id + "]";
}
}
@Service
@Scope("prototype")
public class PrototypeBean {
@Autowired
private SingletonBean singletonBean;
private int id;
private static int static_id = 0;
public PrototypeBean() {
id = static_id++;
}
@Override
public String toString() {
return "id=" + id + ", PrototypeBean [singletonBean=" + singletonBean + "]";
}
}
@Service
@Scope("prototype")
public class PrototypeBean {
@Autowired
private SingletonBean singletonBean;
private int id;
private static int static_id = 0;
public PrototypeBean() {
id = static_id++;
}
@Override
public String toString() {
return "id=" + id + ", PrototypeBean [singletonBean=" + singletonBean + "]";
}
}
答案 1 :(得分:0)
通常在Spring Context中,如果原型bean被注入 singleton bean,父类的属性重写原型bean 范围。
这是真的,但并非总是如此,您可以使用Lookup方法注入来覆盖它,这使您能够在每个请求中注入新的原型对象,检查documentation以获取有关它的完整示例,
对于你的主要问题,单例是在加载上下文时创建的,然后无论是谁调用这个单例的上下文都给出相同的实例,而不考虑谁在进行调用