I’m pretty new to the Springframework (as you will guess) and ran into a situation, where help is desperatly needed.
I do hava a J2EE application here, running on tomcat with lots of old code. Anyway, we decided to use the Spring framework for certain tasks. For example we want to store a security object (containing the username and other authentication related properties) as a session scoped bean.
As there is plenty of old code calling the constructor of this “security object” my question is as following:
Will that object be obtained from the session (in any magic way spring is capable of) or will the constructor call generate a completely new object?
I’ve read something about “autowire mechanism”… would that help me any further?
Thanks for your answers and time!
If your code creates an instance of the security object by calling the constructor of the class i.e. by calling
new Security(), it will get a new instance everytime.Declare a bean for your security object in your spring applicationContext.xml file. To make the security object session scoped, you’ll need to declare its
scopeassessionand make it a proxy:Now, instead of calling
new Security(), the client will get theSecurityobject from Spring application context (see line 1):Spring will take care of creating instances of
Securityfor each session. The object returned by the call at line 1 is not an actualSecurityobject but instead it is a proxy object. WhensecurityObject.doSomething()is called on line 2, the proxy object will look up the actual object created for that session and delegate the call to it. This will be managed by Spring.Note that to get the bean at line 2, you will first need a handle to the ApplicationContext object. How you will get that object will depend on where the calling code is. Edit: An easy way to get it uniformly is by implementing the ApplicationContextAware interface.
Note: Instead of getting the bean from application context, you can get it wired by Spring, but that will require you to declare beans for all the clients that need the security object. Since you are modifying an existing application, I think the above approach is better.