13 spring spring-mvc
在加载Spring的应用程序上下文后,我需要立即发生一些事情.据我了解,我需要创建一个Lifecycle实现并在上下文中放置一个bean引用.所以我在上下文中有类似的东西:
<bean id="mySpringLifecycle" class="com.my.project.MySpringLifecycle" />
Run Code Online (Sandbox Code Playgroud)
该类看起来像这样:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我没有错误,但MySpringLifecycle从未打印出"生命周期已经开始.",我的应用程序启动就好了.
编辑:
这是固定代码:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
作为旁注,我还想提一个我也可以使用的替代解决方案.我的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>
Run Code Online (Sandbox Code Playgroud)
ContextLoaderListener上有一个名为contextInitialized的方法.所以我所做的是创建了我自己的实现,并将其添加到web.xml中.在我的实现中,我扩展了ContextLoaderListener,为contextInitialized方法提供了一个覆盖,首先为该方法调用了super,然后执行了我自己的功能.这只执行一次,看起来效果很好.
两种方法:
实现SmartLifecycle,而不是Lifecycle和确保返回true的isAutoStartup().
实施ApplicationListener<ContextRefreshedEvent>.在这种情况下,只有一种方法可以实现,而不是6 SmartLifecycle.
| 归档时间: |
|
| 查看次数: |
7710 次 |
| 最近记录: |