我是Spring的新手,并试图理解“将原型bean注入单个bean”的概念.根据我的理解在单例中,每个Spring IoC容器只有一个实例,无论你检索它多少次. validator.validate(requestId);,因为仍然没有实例化私有RequestValidator验证器.
我开发了以下示例,在单例bean中,我给出了原型bean的引用,如下所示:
RequestProcessor.java
public class RequestProcessor {
private RequestValidator validator;
public RequestProcessor(){
System.out.println("Constructor:: RequestProcessor instance created!");
}
public void handleRequest(String requestId){
System.out.println("Request ID : "+ requestId);
validator.validate(requestId);
}
public RequestValidator getValidator() {
return validator;
}
public void setValidator(RequestValidator validator) {
this.validator= validator;
}
}
RequestValidator.java
public class RequestValidator {
private List
现在当我调用main方法时,我看到以下输出:
MainDemo.java
public class MainDemo {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
RequestProcessor processor = (RequestProcessor) context.getBean("requestProcessor");
processor.handleRequest("1212");
System.out.println("------------------------");
processor.handleRequest("1213");
}
}
输出是:
Constructor:: RequestProcessor instance created!
Constructor:: RequestValidator instance created!
Request ID : 1212
RequestValidator :1212
------------------------
Request ID : 1213
RequestValidator :1213
现在查看输出,看起来像第二次调用processor.handleRequest(“1213”); bean没有实例化,而是已经实例化的bean被使用,这就是为什么构造函数不会再被调用.所以Prototype bean验证器只作为单例bean使用.
对我来说:预计当我从应用程序上下文中获取requestProcessor时,它将与新的验证器连接,因为我们声明验证器bean是原型范围.但这不会发生.
怎么解决?我的理解是否正确?
其他方式: