For a regular Servlet, I guess you could declare a context listener, but for Spring MVC would Spring make this any easier?
Furthermore, if I define a context listener and then would need to access the beans defined in my servlet.xml
or applicationContext.xml
, how would I get access to them?
Spring has some standard events which you can handle.
To do that, you must create and register a bean that implements the
ApplicationListener
interface, something like this:You then register this bean within your
servlet.xml
orapplicationContext.xml
file:and Spring will notify it when the application context is initialized.
In Spring 3 (if you are using this version), the
ApplicationListener
class is generic and you can declare the event type that you are interested in, and the event will be filtered accordingly. You can simplify a bit your bean code like this:Since Spring 4.2 you can use
@EventListener
(documentation)I had a single page application on entering URL it was creating a HashMap (used by my webpage) which contained data from multiple databases. I did following things to load everything during server start time-
1- Created ContextListenerClass
2- Added below entry in web.xml
3- In my Controller Class updated code to first check for Map in servletContext
With this much change when I start my tomcat it loads dataMap during startTime and puts everything in servletContext which is then used by Controller Class to get results from already populated servletContext .
Create your annotation
Create class
Register this class by @Component annotation or in xml
and use annotation where you wan on any method that you want to run after context initialized, like:
Please follow below step to do some processing after Application Context get loaded i.e application is ready to serve.
Create below annotation i.e
@Retention(RetentionPolicy.RUNTIME) @Target(value= {ElementType.METHOD, ElementType.TYPE}) public @interface AfterApplicationReady {}
2.Create Below Class which is a listener which get call on application ready state.
Finally when you start your Spring application just before log stating application started your listener will be called.