3

我正在使用 Spring 3.2 DispatcherServlet。我正在寻找初始化完成发生的初始化挂钩DispatcherServlet;标准的 Spring 解决方案或 servlet 解决方案。有什么建议么?

作为参考,servlet 启动后的最终日志记录语句如下。我希望我的初始化方法在configured successfully 日志语句之后立即执行。

DEBUG o.s.w.s.DispatcherServlet - Published WebApplicationContext of servlet 'mySpringDispatcherServlet' as ServletContext attribute with name [org.springframework.web.servlet.FrameworkServlet.CONTEXT.mySpringDispatcherServlet] 
INFO  o.s.w.s.DispatcherServlet - FrameworkServlet 'mySpringDispatcherServlet': initialization completed in 5000 ms   
DEBUG o.s.w.s.DispatcherServlet - Servlet 'mySpringDispatcherServlet' configured successfully 

根据我的研究,到目前为止,以下内容还没有达到预期的效果:

  1. 根据这个答案扩展ContextLoaderListener/实施。ServletContextListener
  2. WebApplicationInitializer根据javaoc实现。
  3. 我的豆子使用@PostConstruct成功;我正在寻找一个 Servlet 或容器级别的钩子,它将在容器初始化和后处理 bean 之后执行。
4

4 回答 4

2

根本问题是我无法覆盖final方法HttpsServlet.init()。我找到了一个附近的@Override-able 方法,DispatcherServlet.initWebApplicationContext可以确保我的 bean 和上下文已完全初始化:

@覆盖
受保护的 WebApplicationContext initWebApplicationContext()
{
    WebApplicationContext wac = super.initWebApplicationContext();

    // 通过以下方式对初始化的 Foo bean 进行处理:
    // wac.getBean(Foo.class);

    返回结果;
}
于 2013-06-19T20:38:38.403 回答
1

来自 Spring 的标准和自定义事件

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

@Component
public class ApplicationContextListener implements
                                     ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        System.out.println("ApplicationContext was initialized or refreshed: "
                               + event.getApplicationContext().getDisplayName());
    }

}

上面的事件会在 DispatcherServlet 初始化的时候触发,比如打印的时候:

INFO  org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'ServletName': initialization completed in 1234 ms
于 2014-04-02T19:31:51.040 回答
0

您可以ApplicationListener<ContextStartedEvent>在应用程序上下文中实现。然后将为您的根上下文调用此事件侦听器一次,并为每个servlet 上下文调用一次。

public class StartupListener implements ApplicationListener<ContextStartedEvent> {

    public void onApplicationEvent(ContextStartedEvent event) {
        ApplicationContext context = (ApplicationContext) event.getSource();
        System.out.println("Context '" + context.getDisplayName() + "' started.");
    }

}

如果你在你的servlet 上下文中定义了这个监听器,它应该只为 servlet 上下文本身调用一次。

于 2013-06-19T16:27:51.583 回答
0

试试这个,改变你的端口号。就我而言,我从 server.port=8001 更改为 server.port=8002

于 2021-06-07T07:22:11.017 回答