如何防止SpringBootWebApplication在启动时接受http请求?
我有一个spring boot Web应用程序,前端有角度。当我在Web应用程序仍在启动时使用angular应用程序发送请求时,可能会出现Web应用程序可以接受该请求并尝试处理该请求的情况。我相信应用程序能够在如何防止SpringBootWebApplication在启动时接受http请求?,spring,spring-boot,spring-mvc,Spring,Spring Boot,Spring Mvc,我有一个spring boot Web应用程序,前端有角度。当我在Web应用程序仍在启动时使用angular应用程序发送请求时,可能会出现Web应用程序可以接受该请求并尝试处理该请求的情况。我相信应用程序能够在websecurityConfigureAdapter扩展类初始化时接收请求 当其余的类尚未完全初始化时,这会导致问题。例如,当我尝试注销仍在前端登录的用户时,当webapplication仍在启动时,它可能会导致SQLException,因为它无法找到数据库表user 在初始化最后一个类
websecurityConfigureAdapter
扩展类初始化时接收请求
当其余的类尚未完全初始化时,这会导致问题。例如,当我尝试注销仍在前端登录的用户时,当webapplication仍在启动时,它可能会导致SQLException,因为它无法找到数据库表user
在初始化最后一个类(用
@SpringBootApplication
注释的类)之前,如何防止应用程序接受请求?基于@Fullslack.dev的提示,我提出了以下解决方案
@WebFilter(urlPatterns = {"/*"})
public class MyFilter implements Filter, ApplicationListener<ApplicationReadyEvent> {
private boolean webApplicationReadyToAcceptRequests = false;
@Override
public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
webApplicationReadyToAcceptRequests = true;
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
if(!webApplicationReadyToAcceptRequests) {
httpServletResponse.setHeader("Retry-After","35");
httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "The server is currently starting up. Please try again in a moment.");
return;
}
else
filterChain.doFilter(servletRequest, servletResponse);
}
}
}
这将确保spring知道过滤器的存在。您的数据库表用户是由spring启动应用程序创建的吗?@cmlonder是的。这些表是从实体创建的。这可能有帮助:。最有可能的是
@DependsOn
注释和ApplicationReadyEvent
事件似乎是一个可行的解决方案。但它的工作原理与您预期的类似。Spring开始搜索它的Bean(配置等),并将Bean注入到从您拥有SpringBootApplication的类开始的上下文中(除非您提供另一个上下文进行搜索,否则默认行为是从主类的当前包开始)。您是否使用任何可能有异步调用的反应库?@cmlonder否我不使用。只要在websecurityconfig适配器的configure(HttpSecurity-HttpSecurity)
中定义了API端点,应用程序就能够接收请求
@ComponentScan(basePackages={ "FolderWhereMyFilterIsLocated"})