Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Autowired in ServletContextListener

i hava aclass InitApp

@Component
public class InitApp implements ServletContextListener {

@Autowired
ConfigrationService weatherConfService;

/** Creates a new instance of InitApp */
public InitApp() {
   }

public void contextInitialized(ServletContextEvent servletContextEvent) {
    System.out.println(weatherConfService);
   }
public void contextDestroyed(ServletContextEvent servletContextEvent) {
   }
}

and listener in web.xml:

    <listener>
        <listener-class>com.web.Utils.InitApp</listener-class>
    </listener>

    <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

the confService print --> null what the problem?

like image 973
abdelhady Avatar asked Jul 15 '13 13:07

abdelhady


People also ask

What is the difference between ServletContextEvent and ServletContextListener?

ServletContextEvent class provides alerts/notifications for changes to a web application's servlet context. ServletContextListener is a class that receives alerts/notifications about changes to the servlet context and acts on them.

What is ServletContextListener?

ServletContextListener - Interface for receiving notification events about ServletContext lifecycle changes. javax. servlet. ServletContextAttributeListener - Interface for receiving notification events about ServletContext attribute changes.


2 Answers

A couple of ideas came to me as I was having the same issue.

First one is to use Spring utils to retrieve the bean from the Spring context within the listener:

Ex:

@WebListener
public class CacheInitializationListener implements ServletContextListener {

    /**
     * Initialize the Cache Manager once the application has started
     */
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        CacheManager cacheManager = WebApplicationContextUtils.getRequiredWebApplicationContext(
                sce.getServletContext()).getBean(CacheManager.class);
        try {
            cacheManager.init();
        } catch (Exception e) {
            // rethrow as a runtime exception
            throw new IllegalStateException(e);
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        // TODO Auto-generated method stub

    }
}

This works fine if you only have one or two beans. Otherwise it can get tedious. The other option is to explicitly call upon Spring's Autowire utilities:

@WebListener
public class CacheInitializationListener implements ServletContextListener {

    @Autowired
    private CacheManager cacheManager;

    /**
     * Initialize the Cache once the application has started
     */
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
        try {
            cacheManager.init();
        } catch (Exception e) {
            // rethrow as a runtime exception
            throw new IllegalStateException(e);
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        // TODO Auto-generated method stub

    }
}

The caveat in both these solutions, is that the Spring context must by loaded first before either of these can work. Given that there is no way to define the Listener order using @WebListener, ensure that the Spring ContextLoaderListener is defined in web.xml to force it to be loaded first (listeners defined in the web descriptor are loaded prior to those defined by annotation).

like image 189
Eric B. Avatar answered Oct 04 '22 14:10

Eric B.


By declaring

<listener>
  <listener-class>com.web.Utils.InitApp</listener-class>
</listener>

in your web.xml, you're telling your container to initialize and register an instance of InitApp. As such, that object is not managed by Spring and you cannot @Autowired anything into it.

If your application context is set up to component-scan the com.web.Utils package, then you will have a InitApp bean that isn't registered as a Listener with the container. So even though your other bean will be @Autowired, the servlet container won't ever hit it.

That is the trade-off.

There are workarounds to this if you use programmatic configuration with a ServletContainerInitializer or a WebApplicationInitializer for servlet 3.0. You wouldn't use @Autowired, you would just have setter/getter that you would use to set the instance.

Here's an example

class SpringExample implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        WebApplicationContext context = ...;

        SomeBean someBean = context.getBean(SomeBean.class);
        CustomListener listener = new CustomListener();
        listener.setSomeBean(someBean);

        // register the listener instance
        servletContext.addListener(listener);

        // then register DispatcherServlet and ContextLoaderListener, as appropriate
        ...
    }
}

class CustomListener implements ServletContextListener {
    private SomeBean someBean;

    public SomeBean getSomeBean() {
        return someBean;
    }

    public void setSomeBean(SomeBean someBean) {
        this.someBean = someBean;
    }

    @Override
    public void contextInitialized(ServletContextEvent sce) {
       // do something with someBean
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
    }
}

Note that Spring has some custom implementation of WebApplicationInitializer that are quite sophisticated. You really shouldn't need to implement it directly yourself. The idea remains the same, just deeper in the inheritance hierarchy.

like image 31
Sotirios Delimanolis Avatar answered Oct 04 '22 14:10

Sotirios Delimanolis