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.
ConfigurationService
in you xml Spring configuration, as Nambari pointed out, or you should putcomponent-scan
on a package that containsConfigurationService
and annotate the service with@Component
or@Service
– Finical