I need something to happen immediately after Spring's application context is loaded. As I understand it, I need to create an implementation of Lifecycle and put a bean reference inside the context. So I have something like this in my context:
<bean id="mySpringLifecycle" class="com.my.project.MySpringLifecycle" />
The class looks something like this:
public class MySpringLifecycle implements Lifecycle {
@Override
public void start() {
System.out.println("The lifecycle has started.");
}
@Override
public void stop() {
return;
}
@Override
public boolean isRunning() {
return true;
}
}
I get no errors, but MySpringLifecycle never prints out "The lifecycle has started.", and my application starts just fine.
EDIT:
This is the fixed code:
public class MySpringLifecycle implements SmartLifecycle {
private volatile boolean isRunning = false;
@Override
public boolean isAutoStartup() {
return true;
}
@Override
public void stop(Runnable r) {
System.out.println("STOPPED RUNNABLE!!!");
isRunning = false;
}
@Override
public void start() {
System.out.println("STARTED!!!");
isRunning = true;
}
@Override
public void stop() {
System.out.println("STOPPED!!!");
isRunning = false;
}
@Override
public boolean isRunning() {
return isRunning;
}
@Override
public int getPhase() {
return 1;
}
}
As a side note I also wanted to mention an alternative solution that I may use as well. I have the following in my web.xml:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
The ContextLoaderListener has a method on it called contextInitialized. So what I did was created my own implementation and added that to the web.xml instead. In my implementation I extended ContextLoaderListener, provided an override for the contextInitialized method, called super for that method first, and then executed my own functionality. This gets executed only once, and appears to work well.