最近由.net 转java 开发。在使用Maven 打包Spring boot 项目时遇到了一个坑,现记录下来,供以后参考
Spring boot 内置tomcat,能让我们快速构建web项目。如果要发布在外部的tomcat 上则需要进行一些配置
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.smart.web</groupId>
<artifactId>com-smart-web</artifactId>
<version>1.0.0</version>
<packaging>war</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.5.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- spring-boot web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<!-- 排除内置容器,排除内置容器导出成war包可以让外部容器运行spring-boot项目-->
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--<dependency>-->
<!--<groupId>javax.servlet</groupId>-->
<!--<artifactId>javax.servlet-api</artifactId>-->
<!--</dependency>-->
</dependencies>
<!-- Package as an executable jar -->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
java启动类
启动类必须放在项目的根目录下面
package com;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
/**
* Created by felix on 2017/4/11.
*/
@SpringBootApplication
public class Application extends SpringBootServletInitializer {
//作用类似javaweb中的web.xml,声明web容器的程序入口,
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(Application.class);
}
public static void main(String[] args) {
System.out.println("服务开始启动...");
try {
SpringApplication.run(Application.class, args);
System.out.println("服务已启动!");
}catch (Throwable ex){
System.out.println("服务启动异常!");
}
}
}
Controller 类
package com.smart.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by felix on 2017/4/11.
*/
@RestController
@RequestMapping(value = "/home")
public class HomeController {
@RequestMapping(value="/index",method = RequestMethod.GET)
public String Index(){
return "smart-web";
}
}
使用maven中的package 进行打包,把生成的war包拷贝到tomcat 中的/webapps
发布在tomcat 6中,会导致controller中的方法无法访问,这个问题被坑了好久。
项目发布到tomcat 8中就一切正常了
tomcat 7在电脑上一直启动不成功,所以没有尝试是否可行