[英]Spring framework: what happens when you inject a Java bean into another Java bean but they have different scopes
我是 Java 和 Spring 框架編程的新手。 請考慮以下兩個 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..."); }
}
class AccountService 對於給定的 HTTP session 僅實例化一次。 當它被實例化時,存款者 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. 但是,Depositor class 的 scope 應該是“請求”,即每個請求的實例化......我在這里很困惑,是一個新的 Depositer object 實例化嗎? 還是在整個 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. 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.