Spring Boot Tutorials Part #4: Adding Services in Spring Boot

{getToc} $title={Table of Contents}

Spring Boot Tutorials Part #4: Adding Services in Spring Boot


Introduction

Spring Boot is a popular framework for building web applications and microservices in Java. It provides many features that make development easier and faster, such as auto-configuration, embedded servers, starter dependencies, and more. 

In this blog, we will explore how to use Spring Boot to add some useful services to our web application, such as Actuator, JPA, JDBC, etc. And we will also refer to some examples from https://spring.io/guides/gs/spring-boot/.


What are services in Spring Boot?

Services are classes that contain the business logic of our application. They are annotated with @Service and are usually injected into controllers or other components using dependency injection. Services can also use other services or repositories to access data or perform operations.

For example, we can create a service class that manages the employees of a company with the code bellow:

@Service    
public class EmployeeService {

    // Inject a repository to access employee data
    @Autowired
    private EmployeeRepository employeeRepository;

    // A service method that returns all employees
    public List<Employee> getAllEmployees() {
        return employeeRepository.findAll();
    }

    // A service method that adds a new employee
    public Employee addEmployee(Employee employee) {
        return employeeRepository.save(employee);
    }

    // Other service methods ...

}


How to add Actuator service in Spring Boot?

Actuator is a service that provides production-ready features for monitoring and managing our application. It exposes various endpoints that give us information about the health, metrics, configuration, environment, etc. of our application. And we can also customize or extend the Actuator endpoints to suit our needs.

To add Actuator service in Spring Boot, we need to include this spring-boot-starter-actuator dependency in our pom.xml file:

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

By default, only a few endpoints are exposed over HTTP. And we can configure which endpoints are enabled or exposed using the management.endpoints.web.exposure.include and management.endpoints.web.exposure.exclude properties in the application.properties file. 

For example:

# Expose all endpoints except env and beans
management.endpoints.web.exposure.include=*
management.endpoints.web.exposure.exclude=env,beans

We can then access the Actuator endpoints using the /actuator prefix in our URL. For example:

  • To get the health status of our application: http://localhost:8080/actuator/health
  • To get the metrics of our application: http://localhost:8080/actuator/metrics
  • To get the mappings of our application: http://localhost:8080/actuator/mappings

For more details on Actuator service, please refer to https://docs.spring.io/spring-boot/docs/current/reference/html/actuator.html.


How to add JPA service in Spring Boot?

JPA (Java Persistence API) is a service that provides an abstraction layer for accessing and manipulating data from various sources, such as relational databases, NoSQL databases, etc. It allows us to use Java objects (entities) to represent and query data, without worrying about the underlying implementation details.

To add JPA service in Spring Boot, we need to include this spring-boot-starter-data-jpa dependency in our pom.xml file:

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

And we also need to configure the data source properties in the application.properties file. For example, if we use an H2 in-memory database:

# Enable H2 console
spring.h2.console.enabled=true

# Configure H2 data source
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver
# Configure JPA properties
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

We can then create entity classes that map to our database tables using annotations such as @Entity, @Id, @Column, etc. 

For example:

@Entity
public class Employee {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(nullable = false)
    private String name;
    @Column(nullable = false)
    private String role;

    // Constructors, getters, setters, equals,hashcode, toString ...
}

Now, let's create repository interfaces that extend JpaRepository or other Spring Data interfaces to perform CRUD operations on our entities. 

For example:

public interface EmployeeRepository extends
JpaRepository<Employee, Long> {
    // We can define custom query methods here
    List<Employee> findByRole(String role);
}

And then we can inject and use the repository in our service or controller classes. 

For example:

@Service
public class EmployeeService {
    @Autowired
    private EmployeeRepository employeeRepository;
    // Service methods ...
}
@RestController
@RequestMapping("/employees")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;
    // Controller methods ...
}

For more details on JPA service, please refer to: https://docs.spring.io/spring-data/jpa/docs/current/reference/html/.


How to add JDBC service in Spring Boot?

JDBC (Java Database Connectivity) is a service that provides a low-level API for accessing and manipulating data from relational databases. It allows us to use SQL statements and parameters to query and update data without relying on any ORM framework.

To add JDBC service in Spring Boot, we need to include this spring-boot-starter-jdbc dependency in our pom.xml file:

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

We also need to configure the data source properties in the application.properties file. 
For example, if we use an H2 in-memory database:

# Enable H2 console
spring.h2.console.enabled=true
# Configure H2 data source
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver

Then inject and use the JdbcTemplate class in our service or controller classes to execute SQL queries and updates. 

For example:

@Service
public class EmployeeService {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    // A service method that returns all employees    
    public List<Employee> getAllEmployees() {
        return jdbcTemplate.query("select * from employee", new
BeanPropertyRowMapper<>(Employee.class));
    }
    // A service method that adds a new employee    
    public int addEmployee(Employee employee) {
        return jdbcTemplate.update("insert into employee (name,
role) values (?, ?)", employee.getName(), employee.getRole());
    }
    // Other service methods ...
}

For more details on JDBC service, please refer to: https://docs.spring.io/spring-framework/reference/data-access/jdbc.html.


Conclusion:

We have covered how to add some valuable services to our web application using Spring Boot, such as Actuator, JPA, JDBC and more. We have also shown some examples of how to apply these services in our code. Spring Boot simplifies and accelerates the development of web applications and microservices with various services and features. 

We hope you liked this blog and found it useful. If you have any question or feedback, please don’t hesitate to leave a comment below. Thank you for reading!




Previous Post Next Post