前言
最近,在搞Springboot,新建了一个项目,发现在Intellij Idea中可以通过内置的容器运行,可以正常访问,但是,打成war包后,手动部署到Tomcat后,服务可以正常起来,但是,无法访问资源,总是爆404的错误
原因
最开始,我开始猜想是路径配置有误或者访问的路径有误,顺着这个线索找了下,发现不对;又去看了tomcat的启动日志,和访问日志,均没有任何异常(少了Springboot的logo),而且在tomcat中的manager管理页面中,新建的war项目是确确实实运行了起来的,而且也没有任何异常;如下图
我就开始对比之前建的的项目,发现少了一个继承SpringBootServletInitializer的类,就试着把这个类添加进去,果不其然,运行起来后,就可以访问了
package demo.demo;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(DemoApplication.class);
}
}
通过看SpringBootServletInitializer类注释
/**
* An opinionated {@link WebApplicationInitializer} to run a {@link SpringApplication}
* from a traditional WAR deployment. Binds {@link Servlet}, {@link Filter} and
* {@link ServletContextInitializer} beans from the application context to the server.
* <p>
* To configure the application either override the
* {@link #configure(SpringApplicationBuilder)} method (calling
* {@link SpringApplicationBuilder#sources(Class...)}) or make the initializer itself a
* {@code @Configuration}. If you are using {@link SpringBootServletInitializer} in
* combination with other {@link WebApplicationInitializer WebApplicationInitializers} you
* might also want to add an {@code @Ordered} annotation to configure a specific startup
* order.
* <p>
* Note that a WebApplicationInitializer is only needed if you are building a war file and
* deploying it. If you prefer to run an embedded web server then you won't need this at
* all.
*
* @author Dave Syer
* @author Phillip Webb
* @author Andy Wilkinson
* @since 2.0.0
* @see #configure(SpringApplicationBuilder)
*/
大致的意思就是,如果你构建了一个WAR包,部署在外置的容器中,需要实现这个类,才能正常访问服务
总结
归根结底还是对Springboot不熟悉。以前大学的时候接触过一段时间SSH开发,各种xml配置漫天飞,现在一接触到Springboot省了很多配置文件,确实方便了很多
————————————————
版权声明:本文为CSDN博主「何浪」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/helang296479893/article/details/102824866