I am no sure if my codes is thread safe,anyone can help?
@Aspect
public class MyAspect {
@Autowired
private HttpSession session;
@Before("...")
private void myMethod() {
seesion.getId();
}
}
Because MyAspect's scope is default(singleton),so many request exsits at same time and also many session.OK,Which session I get in my code?Is it thread safe?Or it's a wrong code,if it's wrong,how can I do?
Thanks!
Right, it's OK.
Your MyAspect
should be registered as bean anyway.
It doesn't matter is it AOP Aspect or not: the dependency injection infrastructure the same.
Now about HttpSession
.
This object isn't registered as bean, but for him Spring provide a trick - WebApplicationContextUtils.SessionObjectFactory
. This object is registered as
beanFactory.registerResolvableDependency(HttpSession.class, new SessionObjectFactory());
And when the injection works it wraps SessionObjectFactory
with Proxy
to invoke real methods on demand from ThreadLocal<RequestAttributes>
variable. That mean that each call of your MyAspect.myMethod
does the stuff for concrete HttpSession
, if your current Thread is a Servlet Thread, of course.
So, the answer to your question: yes, it is thread safe.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With