在外部tomcat中執行spring boot應用

luckystar2008發表於2017-07-26

在外部tomcat中執行spring boot應用

預設,Springboot使用內嵌的tomcat來執行springboot應用。如果你想使用外部tomcat來執行,需要做一些修改。

1.在pom.xml中將應用修改為war

2.應用啟動類修改

需要繼承SpringBootServletInitializer,並重寫configure方法。

@SpringBootApplication
@MapperScan("com.ybf.activity.web.mapper")
public class Application extends SpringBootServletInitializer {
    private final static Logger logger = LoggerFactory.getLogger(Application.class);

    @Bean
    public ServletRegistrationBean statViewServlet () {
        ServletRegistrationBean reg = new ServletRegistrationBean();
        reg.setServlet (new StatViewServlet());
        reg.addUrlMappings ("/druid/*");
        return reg;
    }

    @Override
    protected SpringApplicationBuilder configure(
            SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
        logger.info("Application [activity-web] started!");
    }
}

3.新增spring-boot-starter-tomcat依賴

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <scope>provided</scope>
</dependency>

4.使用maven打包

在專案的根目錄執行mvn clean package -DskipTests=true,這樣會自動處理模組間的依賴關係,並且會將該專案的每個模板都進行打包。

打包完畢後,將WAR丟到tomcat就可以跑了。

5.問題記錄

系統環境變數的JDK版本要和你的專案保持一致。

我就是因為不一致找了很久的原因。我的專案是JDK1.8,系統環境變數是JDK1.7,丟到tomcat日誌只有logback初始化的列印,再沒有其他資訊,後面就提示已經啟動。但訪問controller之類的都是404.

相關文章