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

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

	<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

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"/>
Advertisements
This entry was posted in Java, Programming and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s