问题描述
我需要在外部Tomcat(无嵌入式)中启动一个spring boot项目。该应用程序首先根据文档定义必要的接口。问题是从未调用添加的侦听器(我指的是从未调用过的 contextinitialized
方法)。我不明白错误在哪里,我尝试了几种解决方案都无济于事:
@SpringBootApplication
public class TestApplication extends SpringBootServletinitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
SpringApplicationBuilder applicationBuilder = builder.sources(TestApplication.class);
return applicationBuilder;
}
}
TestWebConfig:
@Configuration
@EnableWebMvc
public class TestWebConfig implements WebMvcConfigurer {
}
去调试,接口调用正确:
public class TestWebApplicationInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws servletexception {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(TestWebConfig.class);
ctx.setServletContext(servletContext);
servletContext.addListener(new ContextLoaderListener(ctx));
servletContext.addListener(new TestListener()); // <--- this is the problem
AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
dispatcherContext.register(TestApplication .class);
ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher",new dispatcherServlet(dispatcherContext));
servlet.setLoadOnStartup(1);
servlet.addMapping("/");
}
}
这是未被调用的侦听器。我也试过 @WebListener
和 @ServletComponentScan
注释,但没有。我已经读到只有嵌入式 Tomcat 有效。
public class TestListener implements servletcontextlistener {
private static final Logger logger = LogManager.getLogger();
@Override
public void contextinitialized(ServletContextEvent ctx) {
logger.info("Hello");
}
@Override
public void contextDestroyed(ServletContextEvent arg0){
}
}
我还尝试使用 @Bean
声明侦听器,如帖子中所建议的那样,仍然什么都不做,或者在 WebApplicationInitializer 中执行 @Autowired
以不使用 new
传递它,仍然什么都没有.
你有什么想法吗?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)