Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Session in Spring AOP

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!

like image 298
yybcjq Avatar asked Apr 04 '14 09:04

yybcjq


1 Answers

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.

like image 81
Artem Bilan Avatar answered Nov 15 '22 08:11

Artem Bilan