views:

81

answers:

3

Hi,

Is there a way in Spring to get an object programatically as if it was injected by the xml file.

Here is what i mean

I have this class called securityDelegate. It's instances are always created by spring

<bean id="securityDelegate" class="securityBusinessDelegate" lazy-init="true">
    <property name="securityServiceEJB" ref="securityServiceEJB"/>
    <property name="securityService" ref="securityService"/>
  </bean>

I need to use an instance of this class in a SessionListener, and as I understand, since this is at a servlet level, I can't inject an instance of securityDelegate into my HttpSessionListener implementation.

What I would like to do is to retrieve an instance through java code, inside my implementation, to do something like this

public class SessionListener implements HttpSessionListener {

 //other methods
 @Override
 public void sessionDestroyed(HttpSessionEvent se) {
    //get an instance of securityBusinessDelegate here

    securityBusinessDelegate.doSomething();
 }
}

I seem to recall this was possible last time I used spring (3+ years ago), but I could be confused. Maybe setting up a factory?

Thanks in advance

+3  A: 
    ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(se.getServletContext.());
ctx.getBean("securityDelegate");
ballmw
You'll need to cast the thing you get back to the class you want, "getBean" returns Object.
ballmw
Thanks (insert)
Tom
+2  A: 

For completeness:

import org.springframework.context.ApplicationContext;    
import org.springframework.web.context.support.WebApplicationContextUtils;

public class SessionListener implements HttpSessionListener {

 @Override
 public void sessionDestroyed(HttpSessionEvent se) {
    ServletContext servletCtx = se.getSession().getServletContext();
    ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletCtx);
    T securityBusinessDelegate = (T) ctx.getBean("securityDelegate")

    securityBusinessDelegate.doSomething();
 }
}
DeezCashews
Thanks for chipping in.
Tom
A: 

Yep, use a factory. Just a much more complicated one. DI/IoC Geniuses.

irreputable