Question

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!

Was it helpful?

Solution

Right, it's OK.

  1. Your MyAspect should be registered as bean anyway.

  2. It doesn't matter is it AOP Aspect or not: the dependency injection infrastructure the same.

  3. 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top