spring-boot項目中,默認提供內嵌的tomcat,因此打包直接生成jar包,用Java -jar命令就能夠啓動。java
可是也有必定的需求,會使用外部tomcat來部署項目。下面來看:web
1.新建項目boot-tomcat-testspring
2.pom依賴:(添加spring-boot-starter-tomcat依賴,打包方式爲war)apache
<?xml version="1.0" encoding="UTF-8"?> <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>boot-tomcat</groupId> <artifactId>com.boot.tomcat</artifactId> <version>1.0-SNAPSHOT</version> <!--父依賴包--> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.3.2.RELEASE</version> <relativePath/> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </dependency> </dependencies> <!-- tomcat 打war包 --> <packaging>war</packaging> </project>
3.啓動App繼承SpringBootServletInitializer類,並重寫configure方法tomcat
package boottest; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.context.web.SpringBootServletInitializer; /** * App類描述: * 繼承SpringBootServletInitializer,能夠用tomcat部署 * @author yangzhenlong * @since 2017/5/3 */ @SpringBootApplication public class App extends SpringBootServletInitializer{ @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { return builder.sources(App.class); } public static void main(String[] args) throws Exception { SpringApplication.run(App.class, args); } }
4.Controller:app
package boottest; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * IndexController類描述: * * @author yangzhenlong * @since 2017/5/3 */ @RestController public class IndexController { @RequestMapping("/") public String index(){ return "hello boot"; } }
5.配置項目到tomcat,而後啓動tomcatmaven
訪問:http://localhost:8080/ide
ok了!spring-boot