spring boot 四大组件之Starter

1.概述

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

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

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

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

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

现在我们可以创建一个REST控制器。为简单起见,我们不会使用数据库并只专注于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,包含与Long类型id属性和String类型的value属性。

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

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

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

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

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

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

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

使用模拟环境
使用嵌入式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)));
}
}

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

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

{
entityList.add(new GenericEntity(1l, "entity_1"));
entityList.add(new GenericEntity(2l, "entity_2"));
entityList.add(new GenericEntity(3l, "entity_3"));
entityList.add(new GenericEntity(4l, "entity_4"));
}
//...
}

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

4. The Data JPA Starter
大多数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>

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

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

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

这是JUnit测试:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
public class SpringBootJPATest {

@Autowired
private GenericEntityRepository genericEntityRepository;

@Test
public void givenGenericEntityRepository_whenSaveAndRetreiveEntity_thenOK() {
GenericEntity genericEntity =
genericEntityRepository.save(new GenericEntity("test"));
GenericEntity foundedEntity =
genericEntityRepository.findOne(genericEntity.getId());

assertNotNull(foundedEntity);
assertEquals(genericEntity.getValue(), foundedEntity.getValue());
}
}

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

5.The Mail Starter
企业开发中一个非常常见的任务是发送电子邮件,直接处理Java Mail API通常很困难。

Spring Boot启动程序隐藏了这种复杂性 - 可以通过以下方式指定邮件依赖项:

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

现在我们可以直接使用JavaMailSender,所以让我们编写一些测试。

出于测试目的,我们需要一个简单的SMTP服务器。在这个例子中,我们将使用Wiser。这就是我们如何将它包含在我们的POM中:

<dependency>
<groupId>org.subethamail</groupId>
<artifactId>subethasmtp</artifactId>
<version>3.1.7</version>
<scope>test</scope>
</dependency>

可以在Maven中央存储库中找到最新版本的Wiser 。

以下是测试的源代码:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
public class SpringBootMailTest {
@Autowired
private JavaMailSender javaMailSender;

private Wiser wiser;

private String userTo = "[email protected]";
private String userFrom = "[email protected]";
private String subject = "Test subject";
private String textMail = "Text subject mail";

@Before
public void setUp() throws Exception {
final int TEST_PORT = 25;
wiser = new Wiser(TEST_PORT);
wiser.start();
}

@After
public void tearDown() throws Exception {
wiser.stop();
}

@Test
public void givenMail_whenSendAndReceived_thenCorrect() throws Exception {
SimpleMailMessage message = composeEmailMessage();
javaMailSender.send(message);
List<WiserMessage> messages = wiser.getMessages();

assertThat(messages, hasSize(1));
WiserMessage wiserMessage = messages.get(0);
assertEquals(userFrom, wiserMessage.getEnvelopeSender());
assertEquals(userTo, wiserMessage.getEnvelopeReceiver());
assertEquals(subject, getSubject(wiserMessage));
assertEquals(textMail, getMessage(wiserMessage));
}

private String getMessage(WiserMessage wiserMessage)
throws MessagingException, IOException {
return wiserMessage.getMimeMessage().getContent().toString().trim();
}

private String getSubject(WiserMessage wiserMessage) throws MessagingException {
return wiserMessage.getMimeMessage().getSubject();
}

private SimpleMailMessage composeEmailMessage() {
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setTo(userTo);
mailMessage.setReplyTo(userFrom);
mailMessage.setFrom(userFrom);
mailMessage.setSubject(subject);
mailMessage.setText(textMail);
return mailMessage;
}
}

在测试中,@Before和@After方法负责启动和停止邮件服务器。

请注意,我们在程序中使用的JavaMailSender bean - 这个bean是由Spring Boot自动创建的。

与Boot中的任何其他默认值一样,JavaMailSender的电子邮件设置可以在application.properties中自定义:

spring.mail.host=localhost
spring.mail.port=25
spring.mail.properties.mail.smtp.auth=false

我们在localhost:25上配置了邮件服务器,并且不需要身份验证。

原文地址:https://www.cnblogs.com/bierenbiewo11/p/11888228.html

时间: 2024-07-30 04:49:20

spring boot 四大组件之Starter的相关文章

Spring Boot小组件 - FailureAnalyzer

前言 一个Spring Boot 应用偶尔会因为某些原因启动失败,此时Spring Boot会友好地输出类似于这样一段文字,告诉你发生了什么,甚至应该采取什么行动: *************************** APPLICATION FAILED TO START *************************** Description: Parameter 0 of constructor in com.example.B required a bean of type 'c

阿里P9告诉你 Spring Boot 2.0正式发布,升还是不升呢?

Spring帝国Spring几乎是每一位Java开发人员都耳熟能详的开发框架,不论您是一名初出茅庐的程序员还是经验丰富的老司机,都会对其有一定的了解或使用经验.在现代企业级应用架构中,Spring技术栈几乎成为了Java语言的代名词,那么Spring为什么能够在众多开源框架中脱颖而出,成为业内一致认可的技术解决方案呢?我们不妨从最初的Spring Framework开始,看看它为什么能够横扫千军,一统江湖! 挑战权威,一战成名 2004年3月,Spring的第一个版本以及其创始人Rod John

最火热的极速开发框架Spring Boot

Spring Boot是Spring家族中的一个全新的框架,它用来简化Spring应用程序的创建和开发过程,也可以说Spring Boot能简化我们之前采用Spring mvc + Spring + MyBatis 框架进行开发的过程: 在以往我们采用 Spring mvc + Spring + MyBatis 框架进行开发的时候,搭建和整合三大框架,我们需要做很多工作,比如配置web.xml,配置Spring,配置MyBatis,并将它们整合在一起等,而Spring Boot框架对此开发过程进

Spring Boot Log 日志使用教程

我们编写任何 Spring Boot 程序,可能绕不开的就是 log 日志框架(组件). 在大多数程序员眼中日志是用来定位问题的.这很重要. 本项目源码下载 注意本项目提供的源码已在后期重新编写,有部分日期描述不一致. 如果你只是想知道 Spring boot log 如何使用,请直接观看 3.2 使用 Spring Boot Logback 1 Log 日志概述 1.1 Log 日志组件能干什么 日志能干的事情很多,对于学习程序,测试的工程师来说,日志能够定位问题,解决问题,是最大的功能点.

20191114 Spring Boot官方文档学习(4.7)

4.7.开发Web应用程序 Spring Boot非常适合于Web应用程序开发.您可以使用嵌入式Tomcat,Jetty,Undertow或Netty创建独立的HTTP服务器.大多数Web应用程序都使用该spring-boot-starter-web模块来快速启动和运行.您还可以选择使用spring-boot-starter-webflux模块来构建反应式Web应用程序. 4.7.1.Spring Web MVC框架 在Spring Web MVC框架(通常简称为"Spring MVC"

使用Ratpack和Spring Boot打造高性能的JVM微服务应用

使用Ratpack和Spring Boot打造高性能的JVM微服务应用 这是我为InfoQ翻译的文章,原文地址:Build High Performance JVM Microservices with Ratpack & Spring Boot,InfoQ上的中文地址:使用Ratpack与Spring Boot构建高性能JVM微服务. 在微服务天堂中Ratpack和Spring Boot是天造地设的一对.它们都是以开发者为中心的运行于JVM之上的web框架,侧重于生产率.效率以及轻量级部署.他

Spring Boot笔记(一)

Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置.通过这种方式,Boot致力于在蓬勃发展的快速应用开发领域(rapid application development)成为领导者. Spring Boot 中所有的starter模块命名规则: 官方模块: spring-boot-starter-*,* 代表一种具体的类型 第三方模块:*-spring-

使用Ratpack与Spring Boot构建高性能JVM微服务

在微服务天堂中Ratpack和Spring Boot是天造地设的一对.它们都是以开发者为中心的运行于JVM之上的web框架,侧重于生产率.效率以及轻量级部署.他们在服务程序的开发中带来了各自的好处.Ratpack通过一个高吞吐量.非阻塞式的web层提供了一个反应式编程模型,而且对应用程序结构的定义和HTTP请求过程提供了一个便利的处理程序链:Spring Boot集成了整个Spring生态系统,为应用程序提供了一种简单的方式来配置和启用组件.Ratpack和Spring Boot是构建原生支持计

Spring Boot 乐观锁加锁失败 - 使用AOP恢复错误

之前写了一些辅助工作相关的Spring Boot怎么使用AOP.这里继续正题,怎么减少Spring Boot 乐观锁加锁报错的情况(基本可以解决). 1. 包依赖 spring-boot-starter-data-jpa, Spring Boot的JPA starter h2, H2内存数据库 spring-boot-starter-test,Spring Boot的Junit测试starter 1 <dependency> 2 <groupId>org.springframewo