Java - Initializing the Web App with Springframework
In order to initialize the Web application with Springframework, it is required to detect when context has been initialized. You can achieve it by defining a subclass with deriving ApplicationListener
1
2
3
4
5
6
7
public class ApplicationListenerBean implements
ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent contextEvent) {
// add initialization code
}
}
Then it is required to define this class in application context xml file as shown below example
1
2
<bean id="applicationContextListener" class="com.demo.app.ApplicationListenerBean">
</bean>
If you would like to capture the ApplicationContext in Springframework, you can achieve by subclassing ApplicationContextAware
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class ApplicationContextProvider implements ApplicationContextAware {
private static ApplicationContext ctx = null;
@Override
public void setApplicationContext(ApplicationContext ctx)
throws BeansException {
this.ctx = ctx;
}
public static ApplicationContext getApplicationContext()
throws BeansException {
return ctx;
}
}
// in xml
<bean id="applicationContextProvider" class="com.demo.app.ApplicationContextProvider"/>