Spring - Injecting a Dependency into a Servletcontextlistener

Spring - Injecting a dependency into a ServletContextListener

I resolved this by removing the listener bean and creating a new bean for my properties. I then used the following in my listener, to get the properties bean:

@Override
public void contextInitialized(ServletContextEvent event) {

final WebApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());
final Properties props = (Properties)springContext.getBean("myProps");
}

Spring injection Into Servlet

What you are trying to do will make every Servlet have its own ApplicationContext instance. Maybe this is what you want, but I doubt it. An ApplicationContext should be unique to an application.

The appropriate way to do this is to setup your ApplicationContext in a ServletContextListener.

public class SpringApplicationContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");

sce.getServletContext().setAttribute("applicationContext", ac);
}
... // contextDestroyed
}

Now all your servlets have access to the same ApplicationContext through the ServletContext attributes.

@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);

ApplicationContext ac = (ApplicationContext) config.getServletContext().getAttribute("applicationContext");

this.apiData = (ApiData)ac.getBean("apiData");
this.apiLogger = (ApiLogger)ac.getBean("apiLogger");
}

Injecting static properties in ServletContextListener using Spring

As suggested by http://planproof-fool.blogspot.be/2010/03/spring-setting-static-fields.html

Is this not working for you??

private static Repository repository;

@Autowired(required = true)
private setStaticRepo(Repository localRepo ) {
repository = localRepo;
}

How to inject dependencies into HttpSessionListener, using Spring?

Since the Servlet 3.0 ServletContext has an "addListener" method, instead of adding your listener in your web.xml file you could add through code like so:

@Component
public class MyHttpSessionListener implements javax.servlet.http.HttpSessionListener, ApplicationContextAware {

@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (applicationContext instanceof WebApplicationContext) {
((WebApplicationContext) applicationContext).getServletContext().addListener(this);
} else {
//Either throw an exception or fail gracefully, up to you
throw new RuntimeException("Must be inside a web application context");
}
}
}

which means you can inject normally into the "MyHttpSessionListener" and with this, simply the presence of the bean in your application context will cause the listener to be registered with the container



Related Topics



Leave a reply



Submit