Tom
Tom

Reputation: 45174

Programmatically creating an object in Spring?

Is there a way in Spring to get an object programmatically 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?

Upvotes: 1

Views: 328

Answers (3)

Andrew Wynham
Andrew Wynham

Reputation: 2398

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);
    YourClass securityBusinessDelegate = ctx.getBean(YourClass.class);

    securityBusinessDelegate.doSomething();
 }
}

Upvotes: 2

irreputable
irreputable

Reputation: 45453

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

Upvotes: -1

ballmw
ballmw

Reputation: 955

    ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(se.getServletContext.());
ctx.getBean("securityDelegate");

Upvotes: 3

Related Questions