[英]Spring framework: what happens when you inject a Java bean into another Java bean but they have different scopes
I'm new to Java and Spring framework programming.我是 Java 和 Spring 框架编程的新手。 Please consider the following two Java files:请考虑以下两个 Java 文件:
//AccountService.java
package org.mycompany.accountManagement
@Path("/bankaccount")
@Component
@Scope("session")
public class AccountService
{
private Depositer myDepositer;
@Autowired
pubilc AccountService( Depositer depositer )
{
myDepositer = depositer;
}
}
//Depositer.java
package org.mycompany.accountManagement
@Component
@Scope("request")
public class Depositer
{
public void deposit(){ System.out.println("Depositing..."); }
}
The class AccountService is instantiated only once for a given HTTP session. class AccountService 对于给定的 HTTP session 仅实例化一次。 When it is instantiated, a Depositer object was also instantiated and was kept by AccountService as a private variable.当它被实例化时,存款者 object 也被实例化并由 AccountService 作为私有变量保存。 Since the lifetime of this AccountService object persists throughout the HTTP session, I suppose the Depositor object that it keeps is used throughout the session. Since the lifetime of this AccountService object persists throughout the HTTP session, I suppose the Depositor object that it keeps is used throughout the session. However, the scope of the Depositor class was supposed to be "request," ie, instantiation for every request... I'm confused here, is a new Depositer object instantiated for every request?但是,Depositor class 的 scope 应该是“请求”,即每个请求的实例化......我在这里很困惑,是一个新的 Depositer object 实例化吗? Or is the same Depositor object used throughout the session?还是在整个 session 中使用相同的存款人 object?
Spring uses Proxy pattern internally to solve this and create new instance for request scope bean inside session scoped bean, you know spring has access to every HttpServletRequest
and you can even inject it in your class if you want. Spring uses Proxy pattern internally to solve this and create new instance for request scope bean inside session scoped bean, you know spring has access to every HttpServletRequest
and you can even inject it in your class if you want. so it wraps the session scope bean with a proxy and when you reference request scope bean from the containing session scope bean if it is a new HttpServletRequest
it will create new instance but if it is the same HttpServletRequest
it returns the existing request scope bean. so it wraps the session scope bean with a proxy and when you reference request scope bean from the containing session scope bean if it is a new HttpServletRequest
it will create new instance but if it is the same HttpServletRequest
it returns the existing request scope bean.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.