springboot starter(一)

springboot starter何用?The following explanation is from baeldung.comjava

Dependency management is a critical aspects of any complex project. And doing this manually is less than ideal; the more time you spent on it the less time you have on the other important aspects of the project.web

依赖管理相当重要要, 而且手动依赖管理显得不太完美。你花的时间越多, 你就有更好时间处理其余重要的事情。spring

Spring Boot starters were built to address exactly this problem. Starter POMs are a set of convenient dependency descriptors that you can include in your application. You get a one-stop-shop for all the Spring and related technology that you need, without having to hunt through sample code and copy paste loads of dependency descriptors.sql

Spring Boot starters 就是处理这个问题的。Starter POMs 是一组很方便的依赖描述。不须要为了获取代码要copy and paste 全部的依赖描述。数据库

  1. The Web Starter First, let’s look at developing the REST service; we can use libraries like Spring MVC, Tomcat and Jackson – a lot of dependencies for a single application.

首先, 让咱们看看开发REST 服务; 咱们须要使用Spring MVC tomcat jackson这样的依赖, 来构建单个的app.json

Spring Boot starters can help to reduce the number of manually added dependencies just by adding one dependency. So instead of manually specifying the dependencies just add one starter as in the following example:tomcat

对于上述的作法, Spring Boot starters仅须要一个依赖包就可构建app,极大减小手动添加多个依赖。所以,无需手动指定依赖, 像下边的栗子同样, 仅需增长一个starter: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>springboot

We have created a REST application with quite a minimal configuration.app

仅用不多的配置, 就能够构建一个REST app.less

  1. The Test Starter For testing we usually use the following set of libraries: Spring Test, JUnit, Hamcrest, and Mockito. We can include all of these libraries manually, but Spring Boot starter can be used to automatically include these libraries in the following way:

对于testing 咱们一般用到下边的libraries: Spring Test, JUnit, Hamcrest, Mockito. 咱们能够手动包含全部这些libraries, 可是Spring boot starter能够自动用于包含这些libraries。栗子:

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

Notice that you don’t need to specify the version number of an artifact. Spring Boot will figure out what version to use – all you need to specify is the version of spring-boot-starter-parent artifact. If later on you need to upgrade the Boot library and dependencies, just upgrade the Boot version in one place and it will take care of the rest.

注意你须要指定这个项目的版本号。Spring boot将会分辨出用什么版本。你仅仅须要指定spring-boot-starter-parent的版本。若是后续你升级Boot Libraries和相关依赖, 只须要更新Boot 版本便可, boot本身会兼顾其余依赖包。

Let’s actually test the controller we created in the previous example.

There are two ways to test the controller:

Using the mock environment Using the embedded Servlet container (like Tomcat or Jetty) In this example we’ll use a mock environment:

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

// 初始化mockMvc
[@Before](https://my.oschina.net/u/3870904)
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))); 
}

} The above test calls the /entity/all endpoint and verifies that the JSON response contains 4 elements. For this test to pass, we also have to initialize our list in the controller class:

上面的测试调用 '/entry/all' 而且验证JSON response 包含4个元素。为了让上面的测试经过, 咱们还须要在Controller中初始化请求列表:

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"));
}
//...

} What is important here is that @WebAppConfiguration annotation and MockMVC are part of the spring-test module, hasSize is a Hamcrest matcher, and @Before is a JUnit annotation. These are all available by importing one this one starter dependency.

这儿须要重点说起的是一个注解: @WebAppConfiguration 和 MockMvc是spring-test模块中的一部分, hasSize()是在Hamcrest的matcher, 而且@Before 是JUnit的直接。只须要引入一个starter依赖, 这些依赖的包也就自动包含进来。

  1. The Data JPA Starter Most web applications have some sort of persistence – and that’s quite often JPA. 大多数web应用都有持久化的影子, 而且常常是JPA ....为啥我遇到的都是Mybatis???! Instead of defining all of the associated dependencies manually – let’s go with the starter instead:

无需手动定义全部与JPA 相关的依赖包, 来试试Spring Boot提供的starter: <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> Notice that out of the box we have automatic support for at least the following databases: H2, Derby and Hsqldb. In our example, we’ll use H2.

注意下 '开箱即用' Spring Boot能够自动支持如下类型的数据库: H2, Derby Hsqldb. 本例用到了H2.

Now let’s create the repository for our entity:

1 public interface GenericEntityRepository extends JpaRepository<GenericEntity, Long> {} Time to test the code. Here is the JUnit test:

@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());
}

} We didn’t spend time on specifying the database vendor, URL connection, and credentials. No extra configuration is necessary as we’re benefiting from the solid Boot defaults; but of course all of these details can still be configured if necessary.

这里的栗子没有花费时间来设置DB 提供者, URL Connenction, 证书。正是得益于Spring Boot 的 '开箱即用' 示例代码无需额外的配置;固然,在特殊指定的时候, 仍是须要配置细节。

  1. The Mail Starter A very common task in enterprise development is sending email, and dealing directly with Java Mail API usually can be difficult.

企业开发里发送邮件是很普通的需求,而一般直接利用Java Mail API处理邮件相关需求会很困难??!(应该不困难, 就是繁琐)

Spring Boot starter hides this complexity – mail dependencies can be specified in the following way:

这里, Spring Boot Starter会隐藏这些复杂的东东, 邮件相关依赖以以下方式展现:

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

Now we can directly use the JavaMailSender, so let’s write some tests.

能够直接用JavaMailSender发送邮件。

For the testing purpose, we need a simple SMTP server. In this example, we’ll use Wiser. This is how we can include it in our POM: 为了测试,咱们须要一个简单的SMTP server.在这个栗子里, 使用Wiser.

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

The latest version of Wiser can be found on Maven central repository.

Here is the source code for the test:

@RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(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;
}

} In the test, the @Before and @After methods are in charge of starting and stopping the mail server.

Notice that we’re wiring in the JavaMailSender bean – the bean was automatically created by Spring Boot. 注意咱们直接依赖JavaMailSender bean,无需手动配置, 这个bean自动被Spring Boot建立,并注册到BeanFactory中。

Just like any other defaults in Boot, the email settings for the JavaMailSender can be customized in application.properties:

就像其余的默认同样, JavaMailSender的相关属性也能够在application.yml中设置

spring.mail.host=localhost spring.mail.port=25 spring.mail.properties.mail.smtp.auth=false So we configured the mail server on localhost:25 and we didn’t require authentication.

  1. Conclusion In this article we have given an overview of Starters, explained why we need them and provided examples on how to use them in your projects. 这篇文章说了下Starter的梗概, 解释了为何咱们须要他们而且提供了一些例子来讲明如何在本身的项目里使用他们。

Let’s recap the benefits of using Spring Boot starters: OK, 回顾下Spring boot starter的特长:

increase pom manageability 加强了pom的管理能力 production-ready, tested & supported dependency configurations 提供预生产环境,可测试 支持依赖配置 decrease the overall configuration time for the project 减小项目的整个配置时间。

相关文章
相关标签/搜索