Spring Boot Starters

 

Introduction to Spring Boot Starters

In this post of Spring Boot tutorial, we will introduce Spring Boot Starters to you and will discuss what are the benefits and advantages of Spring Boot Starters.

 

Introduction

Before starting any project be it a small project or an enterprise level application, one of the critical aspects is dependency management, doing it manually for a small application is not a hard job but for complex applications, managing all project dependencies manually is not ideal and prone to many issues as well wasting of the time which can be used in some other important aspects of the project.

One of the fundamental principle behind Spring Boot is to address similar issues. Spring Boot Starters are a set of convenient dependency descriptors which can be easily included in any level of application. These starters work as a bootstrapping process for the Spring related technologies, we no longer need to worry about the dependencies and they will be automatically managed by Spring Boot Starters.      

The starters contain a lot of the dependencies you need to get a project up and running quickly and with a consistent, supported a set of managed transitive dependencies.

 

1. Why Do We Need Starters?

When we start with the Spring Boot, one of the fundamental questions which come to our mind is why do we need Spring Boot Starters? or how these starters will help me in my application?

As mentioned earlier, these starters work to bootstrap your application, all we need is to include correct starter in our application and Spring Boot will ensure that all dependencies required for the chosen starter are in your classpath.To understand it more let’s take an example where we want to build a simple Spring Web-MVC application, to start, we need to think of the following points before working on our web application code.

  • Correct Spring MVC Dependencies.
  • Required dependencies for Web technologies (e.g. We want to use Thymeleaf)
  • We need to make sure that all these dependencies are compatible

 

With Spring Boot Starters, bootstrapping our Spring-MVC web application is straightforward, We need to include spring-boot-starter-web starter in our pom.xml,

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

Above entry in pom.xml will ensure that all required dependencies should be in your classpath and we are all set to work on our web application. There are around 50+  starters offered by Spring Boot excluding third party starters. For the updated list of starters, please refer to  Spring Boot Starter

In this section, I will cover some commonly used starters.

 

2. Web Starter

This is one of the most commonly used Spring Boot Starter, This starter will ensure that all required dependencies to create Spring Web application (including REST) are included in your classpath, it will also add tomcat-starter as default server to run our web application. To include Web Starter in our application, add the following entry in pom.xml.

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

Now we can create our Spring-MVC Controller

 @RestController
    public class SampleController {

        @RequestMapping("/greeting")
        String hello() {
            return "HelloWorld!";
        }
    }

If you run your application and access,http://localhost:8080/greetings you should be able to get “Hello Word” as the response. We created a REST controller with minimal code.

 

3. Data JPA Starter

Most of the application will need persistence mechanism and JPA is established standard for the persistence, Spring Boot Starters comes with JPA Starters, You no longer have to configure those JPA dependencies manually, this can be easily achieved by adding JPA Starter in your application.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
</dependency>

Spring JPA Starter provides automatic support for H2, Derby and Hsqldb. Let’s have a look at how easy is to create a sample JPA application using JPA starter.

@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String firstName;
    private String lastName;

    protected User() {
    }

    public User(String firstName, String lastName) {
        //this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", firstName='" + firstName + '\'' +
                ", lastName='" + lastName + '\'' +
                '}';
    }
}

Here is our UserRepository

public interface UserRepository extends CrudRepository<User,Long> {
    List<User> findUserByLastName(String lastName);
}

Time to test our code, here is the JUnit test

@RunWith(SpringRunner.class)
@SpringBootTest
public class JpademoApplicationTests {

   @Autowired
   UserRepository userRepository;

   @Test
   public void contextLoads() {

        User user = userRepository.save(new User("Demo","User"));
        User searchUser= userRepository.findOne(user.getId());

        assertNotNull(searchUser);
        assertEquals(user.getFirstName(),searchUser.getFirstName());

   }

}

As we saw in above code, you longer need to specify those database configurations or extra DB configurations, by adding JPA starter, many features were available to us out of the box with no need to configure or code. 

You can always change/customize these configurations if needed.

 

4. Mail Starter

Sending email from our application is very common tasks and every application these days require sending emails from the system. Spring Boot Mail starter provides an easy way to handle this feature by hiding all complexities. We can enable email support by adding mail starter in our application.

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

I am using Mailgun as my SMTP Server, here are the SMTP details added to my application.properties file

spring.mail.host=smtp.mailgun.org
[email protected]
spring.mail.password=mypassword
spring.mail.properties.mail.transport.protocol=smtp
spring.mail.properties.mail.smtp.port=587
spring.mail.properties.mail.smtp.auth=true

 

Our EmailService class responsible for sending emails 

@Component
public class JavaEmailService {

    private JavaMailSender mailSender;

    public JavaEmailService(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }

    public void sendEmail(){
        MimeMessagePreparator messagePreparator = mimeMessage -> {

            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
            helper.setFrom("[email protected]");
            helper.setTo("[email protected]");
            helper.setSubject("Sample mail subject");
            helper.setText("Test Email");
        };

        mailSender.send(messagePreparator);
    }
}

We have used  JavaMailSender provided by Spring for email. Time to test the code. Here is the JUnit test

@RunWith(SpringRunner.class)
@SpringBootTest
public class EmailTest {

    @Autowired
    JavaEmailService javaEmailService;

    @Test
    public void sendEmail(){

        javaEmailService.sendEmail();

    }
}

Again, a minimal code and configuration needed to send a simple email. Spring Boot Mail Starter ensured that all required tools are already in place to quickly start working on the real problem.Notice we’re using  JavaMailSender in JavaEmailService bean–Spring Boot automatically created the bean.

[pullquote align=”normal”]Read our article Send Email Using Spring for more detail [/pullquote]

5. Test Starter

We normally use Junit, Mockito or Spring Test for testing Spring Boot application. We can easily include all these libraries in our application by adding Spring Boot Test starter.

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

Spring Boot will automatically find our correct version to be used for our application test. Here is a sample JUnit test

@RunWith(SpringRunner.class)
@SpringBootTest
public class EmailTest {

    @Autowired
    JavaEmailService javaEmailService;

    @Test
    public void sendEmail(){

        javaEmailService.sendEmail();

    }
}

Apart from these starters, below are other frequently used Spring Boot starters.

  • spring-boot-starter-security 
  • spring-boot-starter-web-services
  • spring-boot-starter-integration
  • spring-boot-starter-validation
  • spring-boot-starter-actuator

As mentioned earlier, please refer to Spring Boot Starter for up-to-date list of the starters provided by Spring Boot.

 

Summary

This article provides an Introduction to Spring Boot Starters, we discussed why do we need these starters and how they can help us to quickly bootstrap our application. We explored some of the most commonly used Spring Boot Starters.

Suggested reading

Building an Application with Spring Boot

Comments are closed.