Spring Boot Starters介绍
对于任何一个复杂项目来说,依赖关系都是一个非常需要注意和消息的方面,虽然重要,但是我们也不需要花太多的时间在上面,因为依赖毕竟只是框架,我们重点需要关注的还是程序业务本身。
这就是为什么会有Spring Boot starters的原因。Starter POMs 是一系列可以被引用的依赖集合,只需要引用一次就可以获得所有需要使用到的依赖。
Spring Boot有超过30个starts, 本文将介绍比较常用到的几个。
Web Start
如果我们需要开发MVC程序或者REST服务,那么我们需要使用到Spring MVC,Tomcat,JSON等一系列的依赖。但是使用Spring Boot Start,一个依赖就够了:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
现在我们就可以创建REST Controller了:
@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();
}
}
这样我们就完成了一个非常简单的Spring Web程序。
Test Starter
在测试中,我们通常会用到Spring Test, JUnit, Hamcrest, 和 Mockito这些依赖,Spring也有一个starter集合:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
注意,你并不需要指定artifact的版本号,因为这一切都是从spring-boot-starter-parent 的版本号继承过来的。后面升级的话,只需要升级parent的版本即可。具体的应用可以看下本文的例子。
接下来让我们测试一下刚刚创建的controller:
这里我们使用mock。
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(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。
这里@WebAppConfiguration 和 MockMVC 是属于 spring-test 模块, hasSize 是一个Hamcrest 的匹配器, @Before 是一个 JUnit 注解.所有的一切,都包含在一个starter中。
Data JPA Starter
如果想使用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>
我们接下来创建一个repository:
public interface GenericEntityRepository extends JpaRepository<GenericEntity, Long> {}
然后是JUnit测试:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(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.findById(genericEntity.getId()).orElse(null);
assertNotNull(foundedEntity);
assertEquals(genericEntity.getValue(), foundedEntity.getValue());
}
}
这里我们测试了JPA自带的save, findById方法。 可以看到我们没有做任何的配置,Spring boot自动帮我们完成了所有操作。
Mail Starter
在企业开发中,发送邮件是一件非常常见的事情,如果直接使用 Java Mail API会比较复杂。如果使用Spring boot:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
这样我们就可以直接使用JavaMailSender,前提是需要配置mail的连接属性如下:
spring.mail.host=localhost
spring.mail.port=25
spring.mail.default-encoding=UTF-8
接下来我们来写一些测试案例。
为了发送邮件,我们需要一个简单的SMTP服务器。在本例中,我们使用Wiser。
<dependency>
<groupId>org.subethamail</groupId>
<artifactId>subethasmtp</artifactId>
<version>3.1.7</version>
<scope>test</scope>
</dependency>
下面是如何发送的代码:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class SpringBootMailTest {
@Autowired
private JavaMailSender javaMailSender;
private Wiser wiser;
private String userTo = "user2@localhost";
private String userFrom = "user1@localhost";
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 分别用来启动和关闭邮件服务器。
结论
本文介绍了一些常用的starts,具体例子可以参考 spring-boot-starts
更多教程请参考 flydean的博客
Spring Boot Starters介绍的更多相关文章
- 54 个官方 Spring Boot Starters 出炉!别再重复造轮子了…….
在之前的文章,栈长介绍了 Spring Boot Starters,不清楚的可以点击链接进去看下. 前段时间 Spring Boot 2.4.0 也发布了,本文栈长再详细总结下最新的 Spring B ...
- Spring Boot Starters到底怎么回事?
前言 上周看了一篇.你一直在用的Spring Boot Starters究竟是怎么回事(https://www.cnblogs.com/fengzheng/p/10947585.html) 感觉终 ...
- Spring Boot Starters
Spring Boot Starters 摘自 https://www.nosuchfield.com/2017/10/15/Spring-Boot-Starters/ 2017-10-15 Spri ...
- spring boot入门 -- 介绍和第一个例子
"越来越多的企业选择使用spring boot 开发系统,spring boot牛在什么地方?难不难学?心动不如行动,让我们一起开始学习吧!" 使用Spring boot ,可以轻 ...
- Spring Boot Starter 介绍
http://www.baeldung.com/spring-boot-starters 作者:baeldung 译者:http://oopsguy.com 1.概述 依赖管理是任何复杂项目的关键部分 ...
- Spring Boot Starters 列表
Spring Boot application starters 名称 描述 Pom spring-boot-starter 核心starter,包括自动配置支持,日志和YAML Pom spring ...
- Spring Boot Starters启动器
Starters是什么? Starters可以理解为启动器,它包含了一系列可以集成到应用里面的依赖包,你可以一站式集成Spring及其他技术,而不需要到处找示例代码和依赖包.如你想使用Spring J ...
- Spring Boot Starters是什么?
版权声明:该文转自: http://www.nosuchfield.com/2017/10/15/Spring-Boot-Starters/.版权归原创作者,在此对原作者的付出表示感谢! starte ...
- 你一直在用的 Spring Boot Starters 究竟是怎么回事
Spring Boot 对比 Spring MVC 最大的优点就是使用简单,约定大于配置.不会像之前用 Spring MVC 的时候,时不时被 xml 配置文件搞的晕头转向,冷不防还因为 xml 配置 ...
随机推荐
- 8.MSFvenom
Meterpreter 01 Meterpreter API调用 Meterpreter提供了多种APl调用,在编写自己的脚本时可以使用这些API来提供额外功能或定制功能. 关于ruby的更多信息,请 ...
- 高性能/并发的保证-Netty在Redisson的应用
前言 Redisson Github: https://github.com/redisson/redisson Redisson 官网:https://redisson.pro/ Redis ...
- Spring Taco Cloud——design视图的创建(含thymeleaf模板遇到的一些小问题)
先来看下综合前两篇内容加上本次视图的成果 可能不是很美观,因为并没有加css样式,我想等整个项目有个差不多的功能实现后再进行页面优化,请谅解 下面我贴上自己定义修改过的Taco的design视图代 ...
- .NET Core项目部署到Linux(Centos7)(九)防火墙配置,允许外网或局域网访问.NET Core站点
目录 1.前言 2.环境和软件的准备 3.创建.NET Core API项目 4.VMware Workstation虚拟机及Centos 7安装 5.Centos 7安装.NET Core环境 6. ...
- SpringMVC(三):转发和重定型
本文是按照狂神说的教学视频学习的笔记,强力推荐,教学深入浅出一遍就懂!b站搜索狂神说或点击下面链接 https://space.bilibili.com/95256449?spm_id_from=33 ...
- Python模块---制作属于自己的有声小说
操作环境 Python版本: anaconda3 python3.7.4 操作系统: Ubuntu19.10 编译器: pycharm社区版 用到的模块: pyttsx3,requests pysst ...
- VSCode 初次写vue项目并一键生成.vue模版
VSCode 写vue项目一键生成.vue模版 1.新建代码片段 文件-->首选项-->用户代码片段-->点击新建代码片段--取名vue.json 确定 2.配置快捷生成的vue模板 ...
- k8s集群搭建笔记(细节有解释哦)
本文中所有带引号的命令,请手动输入引号,不知道为什么博客里输入引号,总是自动转换成了中文 基本组成 pod:k8s 最小单位,类似docker的容器(也许) 资源清单:资源.资源清单语法.pod生命周 ...
- Tcl编程第三天,数学运算
1.tcl语言没有自己的数学计算,如果想要使用数学公式,必须得用C语言的库.使用方法如下. #!/usr/bin/tclsh set value [expr 8/5] puts $value set ...
- coding++:漫画版-了解什么是分布式事务?
————— 第二天 ————— ———————————— 假如没有分布式事务: 在一系列微服务系统当中,假如不存在分布式事务,会发生什么呢?让我们以互联网中常用的交易业务为例子: 上图中包含了库存 ...