Introduction to Spring Boot Starters

Article Directory


Dependencies are a very important aspect of any complex project that requires attention and information. Important as they are, we don't need to spend too much time on them, because dependencies are just a framework. We focus on the program business itself.

That's why there are Spring Boot starters.Starter POMs are a set of dependencies that can be referenced, and you only need to reference them once to get all the dependencies you need to use.

Spring Boot has more than 30 starts, and this article will introduce some of the more common ones.

Web Start

If we need to develop MVC programs or REST services, we need to use a range of dependencies such as Spring MVC, Tomcat,JSON, and so on.But with Spring Boot Start, one dependency is enough:

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

Now we can create the 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();
    }
}

This completes a very simple Spring Web program.

Test Starter

In testing, we usually use Spring Test, JUnit, Hamcrest, and Mocokito dependencies, Spring also has a starter collection:

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

Note that you do not need to specify the version number of the artifact, because everything is inherited from the version number of spring-boot-starter-parent.If you upgrade later, you only need to upgrade the parent version.Examples of specific applications can be found in this article.

Next let's test the controller we just created:

Here we use 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)));
    }
}

In the example above, we tested the / entity/all interface and validated the returned JSON.

Here @WebAppConfiguration and MockMVC are spring-test modules, hasSize is a matcher for Hamcrest, and @Before is a JUnit annotation. Everything is contained in a starter.

Data JPA Starter

If you want to use JPA, we can do this:

<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>

Let's create a repository next:

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

Then there is the JUnit test:

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

Here we test the save, findById method that comes with JPA.You can see that we haven't done any configuration and Spring boot has automatically helped us do everything.

Mail Starter

Sending e-mail is a very common thing in enterprise development and can be complicated if you use the Java Mail API directly.If using Spring boot:

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

This allows us to use JavaMailSender directly if we need to configure the following connection properties for mail:

spring.mail.host=localhost
spring.mail.port=25
spring.mail.default-encoding=UTF-8

Next, let's write some test cases.

To send mail, we need a simple SMTP server.In this case, we use Wiser.

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

Here's how to send the code:

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

In the example above, @Before and @After are used to start and shut down mail servers, respectively.

conclusion

This paper introduces some common starts, and gives some examples for reference. spring-boot-starts

Refer to more tutorials Fldean's Blog

84 original articles published. 85% praised. 250,000 visits+
Private letter follow

Keywords: Spring Junit REST JSON

Added by haironfire on Thu, 23 Jan 2020 03:04:14 +0200