views:

61

answers:

2

Hey there! 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!

+1  A: 

If you use the new operator, then you are constructed the object yourself and the constructor is called. Spring is not involved when creating an object via new.

matt b
+1  A: 

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 scope as session and make it a proxy:

<bean id="securityObject" class="com.xyz.Security" scope="session">
    <aop:scoped-proxy /> <!-- important -->
</bean>

Now, instead of calling new Security(), the client will get the Security object from Spring application context (see line 1):

void someMethod() {
    //...
    Security securityObject = applicationContext.getBean("securityObject"); // 1
    securityObject.doSomething(); // 2
    //...
}

Spring will take care of creating instances of Security for each session. The object returned by the call at line 1 is not an actual Security object but instead it is a proxy object. When securityObject.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.

Samit G.