Spring Boot Starters简单介绍

1.概述

依赖管理是任何复杂项目的关键方面。手动完成此操作并不理想; 你花在它上面的时间越多,你在项目的其他重要方面所花费的时间就越少。

构建Spring Boot启动器是为了解决这个问题。Starter POM是一组方便的依赖描述符,您可以在应用程序中包含这些描述符。您可以获得所需的所有Spring和相关技术的一站式服务,而无需搜索示例代码并复制粘贴依赖描述符。

有超过30个启动器 - 让我们在以下部分中看到它们中的一些。

2.Web Starter(servlet容器)

首先,我们来看看开发REST服务; 我们可以使用像Spring MVC,Tomcat和Jackson这样的库 - 对于单个应用程序来说有很多依赖关系。

Spring Boot启动器可以通过添加一个依赖项来帮助减少手动添加的依赖项的数量。因此,不是手动指定依赖项,而是添加一个启动器,如以下示例所示:

1 <dependency>
2     <groupId>org.springframework.boot</groupId>
3     <artifactId>spring-boot-starter-web</artifactId>
4 </dependency>

现在我们可以创建一个REST控制器。为简单起见,我们使用一个简单的REST控制器:

 1 @RestController
 2 public class GenericEntityController {
 3     private List<GenericEntity> entityList = new ArrayList<>();
 4  
 5     @RequestMapping("/entity/all")
 6     public List<GenericEntity> findAll() {
 7         return entityList;
 8     }
 9  
10     @RequestMapping(value = "/entity", method = RequestMethod.POST)
11     public GenericEntity addEntity(GenericEntity entity) {
12         entityList.add(entity);
13         return entity;
14     }
15  
16     @RequestMapping("/entity/findby/{id}")
17     public GenericEntity findById(@PathVariable Long id) {
18         return entityList.stream().
19                  filter(entity -> entity.getId().equals(id)).
20                    findFirst().get();
21     }
22 }
 

GenericEntity是一个简单的bean

就是这样 - 在应用程序运行时,您可以访问http://localhost:8080/entity/all并检查控制器是否正常工作。

我们已经创建了一个具有相当小配置的REST应用程序。so easy

3.测试入门

对于测试,我们通常使用以下一组库:Spring Test,JUnit,Hamcrest和Mockito(后面两个主要用于代理、重写对象进行测试)。我们可以手动包含所有这些库,但可以使用Spring Boot starter以下列方式自动包含这些库:

1 <dependency>
2     <groupId>org.springframework.boot</groupId>
3     <artifactId>spring-boot-starter-test</artifactId>
4     <scope>test</scope>
5 </dependency>
 

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

让我们实际测试我们在前一个例子中创建的控制器。

有两种方法可以测试控制器:

  • 使用模拟环境
  • 使用嵌入式Servlet容器(如Tomcat或Jetty)

在这个例子中,我们将使用模拟环境:

 1 @RunWith(SpringJUnit4ClassRunner.class)
 2 @SpringApplicationConfiguration(classes = Application.class)
 3 @WebAppConfiguration
 4 public class SpringBootApplicationIntegrationTest {
 5     @Autowired
 6     private WebApplicationContext webApplicationContext;
 7     private MockMvc mockMvc;
 8  
 9     @Before
10     public void setupMockMvc() {
11         mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
12     }
13  
14     @Test
15     public void givenRequestHasBeenMade_whenMeetsAllOfGivenConditions_thenCorrect()
16       throws Exception { 
17         MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(),
18         MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
19         mockMvc.perform(MockMvcRequestBuilders.get("/entity/all")).
20         andExpect(MockMvcResultMatchers.status().isOk()).
21         andExpect(MockMvcResultMatchers.content().contentType(contentType)).
22         andExpect(jsonPath("$", hasSize(4))); 
23     } 
24 }

上面的测试调用/entity/all 端点并验证JSON响应是否包含4个元素。要通过此测试,我们还必须在控制器类中初始化我们的列表:

 1 public class GenericEntityController {
 2     private List<GenericEntity> entityList = new ArrayList<>();
 3  
 4     {
 5         entityList.add(new GenericEntity(1l, "entity_1"));
 6         entityList.add(new GenericEntity(2l, "entity_2"));
 7         entityList.add(new GenericEntity(3l, "entity_3"));
 8         entityList.add(new GenericEntity(4l, "entity_4"));
 9     }
10     //...
11 }

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

4. Data JPA Starter

大多数Web应用程序都有某种持久化方法 - 这通常是JPA。

下面不是手动定义所有相关的依赖项 - 而是改为使用启动器:

1 <dependency>
2     <groupId>org.springframework.boot</groupId>
3     <artifactId>spring-boot-starter-data-jpa</artifactId>
4 </dependency>
5 <dependency>
6     <groupId>com.h2database</groupId>
7     <artifactId>h2</artifactId>
8     <scope>runtime</scope>
9 </dependency>

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

现在让我们为我们的实体创建存储库:(下面一行代码就完成了jps存储库的配置,常用实现方法由jpa框架提供,我们只要继承接口,指定实体类即可)

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

是时候测试代码了。这是JUnit测试:

 1 @RunWith(SpringJUnit4ClassRunner.class)
 2 @SpringApplicationConfiguration(classes = Application.class)
 3 public class SpringBootJPATest {
 4      
 5     @Autowired
 6     private GenericEntityRepository genericEntityRepository;
 7  
 8     @Test
 9     public void givenGenericEntityRepository_whenSaveAndRetreiveEntity_thenOK() {
10         GenericEntity genericEntity = 
11           genericEntityRepository.save(new GenericEntity("test"));
12         GenericEntity foundedEntity = 
13           genericEntityRepository.findOne(genericEntity.getId());
14          
15         assertNotNull(foundedEntity);
16         assertEquals(genericEntity.getValue(), foundedEntity.getValue());
17     }
18 }

我们没有花时间指定数据库供应商,URL连接和凭据。不需要额外的配置,因为我们从可靠的Boot默认值中受益; 但当然,如有必要,仍可配置所有这些细节。

springboot基于自动配置,如果我们不设置的话,其会根据我们的classpath(如这里的h2数据库)自动帮我们初始化一些bean实例(包括数据源)。但是一般有些bean我们还是希望自己实例化,可以增加定制的配置信息。

5. 结论

在本文中,我们概述了Starters,解释了我们为什么需要它们,并提供了有关如何在项目中使用它们的示例。

让我们回顾一下使用Spring Boot启动器的好处:

  • 增加pom可管理性(无需手动配置各依赖项的版本)
  • 生产就绪,测试和支持的依赖配置(一个starter中包含了该功能所需要的所有包,配置起来简单方便)
  • 减少项目的总体配置时间

猜你喜欢

转载自www.cnblogs.com/gc65/p/10612013.html