pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.BUILD-SNAPSHOT</version>
</parent>
- 这个starter提供了一些有用的maven默认值,但不包含任何依赖库。
- 提供了依赖管理功能,让我们可以不用指定依赖库的版本。
- 其他的starter提供的是在开发某个具体应用的时候很可能需要的依赖。
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
- 我们要开发一个web应用,所以添加了这个starter。可以看到,没有指定version,因为parent为我们默认指定了合适的version。如果需要特定版本,也开始在这里加上version。
- 添加依赖:spring boot 自身和tomcat web server。
controller
// file:src/main/java/Example.java
import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.web.bind.annotation.*;
@RestController
@EnableAutoConfiguration
public class Example {
@RequestMapping("/")
String home() {
return "Hello World!";
}
public static void main(String[] args) throws Exception {
SpringApplication.run(Example.class, args);
}
}
- @RestController 注解这是一个web controller,能够处理web请求。Rest:处理结果当作字符串返回给web请求。
- @RequestMapping 注解路由信息,当接收到对这个路径的请求的时候,调用这个方法。这两个注解都是spring mvc组件的注解。
- @EnableAutoConfiguration 告诉spring根据我们添加的依赖信息,自动推测配置信息。而spring-boot-starter-web添加了tomcat和spring mvc依赖,所以它会推测这是一个web应用,并进行配置。
- SpringApplication run方法启动应用:自动配置的tomcat。
运行应用
- spring-boot-starter-parent POM中定义了goal
run
,在project根目录下,可以这样启动应用:
mvn spring-boot:run
- 如果启动正常,可以通过浏览器查看结果了: http://localhost:8080
创建可执行的jar
需要添加插件来打包。
在前面提到的pom.xml中添加以下内容:
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
spring-boot-starter-parent 中包含了用于goal repackage
的 executions 配置。如果没有spring-boot-starter-parent POM,就需要我们手动定义这个配置,比如这样:
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.0.0.BUILD-SNAPSHOT</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
注意 这里的version
。
上面这个例子,在maven 的package
phase
,repackage
所有依赖包(* 包括 provided 依赖包)。
可以通过设定,排除某些依赖包,比如这样:
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.0.0.BUILD-SNAPSHOT</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
<configuration>
<excludes>
<exclude>
<groupId>com.foo</groupId>
<artifactId>bar</artifactId>
</exclude>
</excludes>
<excludeArtifactIds>my-lib,another-lib</excludeArtifactIds>
<excludeGroupIds>com.foo</excludeGroupIds>
</configuration>
</plugin>
使用 java -jar
启动上面打包后的应用。
以上