Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if Spring Scope is active

How can I test if the Session scope is active in Spring? for example, at startup some classes need a User object which is Session scoped, than i return a mock User object.

the bean in question is declared with aop:scoped-proxy. how can i test if the session scope is active?

like image 505
Andreas Petersson Avatar asked Jan 30 '26 22:01

Andreas Petersson


2 Answers

As the spring reference manual states in Chapter 3, session scope:

Scopes a single bean definition to the lifecycle of a HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.

Your code, if invoked via a web-aware Spring ApplicationContext (most likely an XMLWebApplicationContext), will automatically be injected with different session scoped beans as they are invoked by different users as long as the proper spring configuration is set up to inject these session scoped beans. Then, your code can ignore where they came from and focus on using the user attributes, etc, found in the session scoped bean - without worrying what actually injected the property.

So, I guess the true answer is that you cannot test this - but nor do you need to - if someone is asking you to do this, then "they're doing it wrong".

like image 143
MetroidFan2002 Avatar answered Feb 01 '26 20:02

MetroidFan2002


the trick was to create a factory, obtain aop-scoped proxy from the factory and run any method that requires the actual object to be there and the scope, too.

then catch a BeanCreationException to detect the inactive scope.

like image 30
Andreas Petersson Avatar answered Feb 01 '26 19:02

Andreas Petersson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!