什么是Spring Boot Starters?

Spring Boot Starter顾名思义是为不同目的启动Spring Boot应用程序。比如:
spring-boot-starter-parent:它是一个特殊的启动器,提供有用的Maven默认值。它在POM的父节中使用。
spring-boot-starter-web:使用MVC构建Web和RESTful应用程序的入门者。
spring-boot-starter-security:使用Spring Security的入门者。
spring-boot-starter-web-services:使用Spring Web服务的初学者。
spring-boot-starter-thymeleaf:使用Thymeleaf视图的Spring MVC的初学者。
spring-boot-starter-freemarker:使用FreeMarker视图启动Spring MVC。
spring-boot-starter-test:单元测试和集成测试,默认引用。
spring-boot-starter-jdbc: 传统 JDBC
spring-boot-starter-hateoas: 增加 HATEOAS 特性到服务。
spring-boot-starter-security: 使用spring安全实现验证和授权。
spring-boot-starter-data-jpa: Spring Data JPA Hibernate支持
spring-boot-starter-cache: 激活 Spring Framework的缓存支持

这些启动器需要配置在maven的pom.xml中,运行时这些包jar在classpath类路径中就会被加载。下面是标准的pom.xml:


<?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>com.concretepage</groupId>
<artifactId>spring-boot-app</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>spring-boot-app</name>
<description>Spring Boot Application</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
<relativePath/>
</parent>
<properties>
<java.version>9</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

可以通过https://start.spring.io选择组件方式,或通过Idea等开发工具Spring导航选择组件,就会自动生成这个pom.xml文件。

下面介绍几个常用的Starter:

Web
以前开发REST服务可能需要手工在pom.xml加入像Spring MVC,Tomcat和Jackson这些库的依赖项,Spring Boot启动器只要添加一个依赖项就可以了:


<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

现在我们可以创建一个REST控制器:

@RestController
public class GenericEntityController {
private List<GenericEntity> entityList = new ArrayList<>();

@RequestMapping("/entity/all")
public List<GenericEntity> findAll() {
return entityList;
}

@RequestMapping(value = "/entity", method = RequestMethod.POST)
public GenericEntity addEntity(GenericEntity entity) {
entityList.add(entity);
return entity;
}

@RequestMapping("/entity/findby/{id}")
public GenericEntity findById(@PathVariable Long id) {
return entityList.stream().
filter(entity -> entity.getId().equals(id)).
findFirst().get();
}
}

GenericEntity是一个简单的bean,有一个ID类型的字段和字符串。
启动这个应用程序运行时,访问http:// localhost:8080/entity/all

测试
为了测试,我们通常使用以下一组库:Spring Test,JUnit,Hamcrest和Mockito。我们可以手动包含所有这些库,但可以使用Spring Boot starter以下列方式自动包含这些库:


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

无需指定版本号。Spring Boot将自己确定要使用的版本 - 你需要指定的是spring-boot-starter-parent版本即可的版本。如果以后需要升级Boot库和依赖项,只需在一个地方升级Boot版本,Spring Boot将负责其余的工作。

有两种方法可以测试REST控制器:
1.使用模拟环境
2.使用嵌入式Servlet容器(如Tomcat或Jetty)
下面使用使用模拟环境:


@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
public class SpringBootApplicationIntegrationTest {
@Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;

@Before
public void setupMockMvc() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}

@Test
public void givenRequestHasBeenMade_whenMeetsAllOfGivenConditions_thenCorrect()
throws Exception {
MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(),
MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
mockMvc.perform(MockMvcRequestBuilders.get("/entity/all")).
andExpect(MockMvcResultMatchers.status().isOk()).
andExpect(MockMvcResultMatchers.content().contentType(contentType)).
andExpect(jsonPath("$", hasSize(4)));
}
}

重要的是:@WebAppConfiguration注释和MockMVC是spring-test模块的一部分,hasSize是一个Hamcrest匹配器,而@Before是一个JUnit注释。这些都可以通过导入这一个启动器依赖项来获得。

JPA
大多数Web应用程序都具有某种数据库访问 - 通常是JPA:


<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>

请注意,Springboot开箱即用特性可以至少自动支持以下数据库:H2,Derby和Hsqldb。在我们的例子中,我们将使用H2。

为我们的实体创建存储库:


public interface GenericEntityRepository extends JpaRepository<GenericEntity, Long> {}

这里没有指定数据库供应商,URL连接和用户名密码。这些不需要额外的配置,因为我们从可靠的Boot默认值中受益; 但当然,如使用MySQL Oracle等数据库需要在application.propertie或yaml中配置所有这些细节。这些配置都是外部化的。