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 減小項目的整個配置時間。

相關文章
相關標籤/搜索