I'm new to Java and Spring framework programming. Please consider the following two Java files:
//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. When it is instantiated, a Depositer object was also instantiated and was kept by AccountService as a private variable. 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? Or is the same Depositor object used throughout the session?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.