Spring Boot Dependencies Library

Apache Camel

1

If you want to start with a new project, then go to   start.spring.io and provide configuration details (Java version, Spring boot version) and choose Apache Camel as a dependency. Download and open it in your favorite Java editor.

You can also extend any existing Spring Boot application in your local by adding the below dependency to your project.

groupId org.apache.camel.springboot
artifactId camel-spring-boot-starter
version 3.7.0

2

Let’s verify Apache Camel by creating a simple Route. We will create a simple route using the File component. This component will move files from one folder to another. To create a route, we need to extend RouteBuilder and override its configure() method. Copy below code snippet into your project.

import org.apache.camel.builder.RouteBuilder;
import org.springframework.stereotype.Component;

@Component
public class FileRoute extends RouteBuilder {
    @Override
    public void configure() throws Exception {
        from("file:<source_folder>?noop=false")
                .to("file:<destination_folder>");
    }
}

Create new source and destination folders in your local and update <source_folder> and <destination_folder> to point to newly created folders.

3

Update application.properties file. We need to keep the application up running because our FileRoute need to look for files in the source folder, so add the below property, this will keep the main thread alive, or another option is to add spring-boot-starter-web dependency in the pom.xml file.

camel.springboot.main-run-controller=true

4

Run Spring Boot application. Once the application is up, then create a file in <source_folder>, and as soon as the file got created then Apache camel will move it to <destination_folder>

5

Now we have Spring Boot project with Apache Camel running.

H2 Database

1

Create a new project by going to   start.spring.io and provide configuration details (Java version, Spring boot version) and choose H2 Database, Spring Data JPA and Spring Web as a dependencies. Download and open it in your Java editor.

You can also extend any existing Spring Boot application in your local by adding the below dependencies to that project.

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

2

Update application.properties file with below properties

spring.datasource.url=jdbc:h2:mem:empdb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true
spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true

This will create a in-memory database with name empdb and enables H2 DB web console. Because it is an in-memory database, so data will lose once we restart the application. To save data in a file, update the property spring.datasource.url with value jdbc:h2:file:./empdb

3

Create a new class called User in the project with the below content.

@Entity
public class User {
    @Id
    private String userId;
    private String firstName;
    private String lastName;

    public User() {}

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

Create a UserRepository interface which extends JpaRepository

public interface UserRepository extends JpaRepository<User, String> {}

Create a UserRepoInitializer class

@Component
class UserRepoInitializer implements CommandLineRunner {
  @Autowired
  UserRepository userRepository;
  @Override
  public void run(String... args) throws Exception {
    Stream.of(new User(UUID.randomUUID().toString(), "Amanda", ""),
        new User(UUID.randomUUID().toString(), "Hannah", ""),
        new User(UUID.randomUUID().toString(), "Anna", ""),
        new User(UUID.randomUUID().toString(), "Audrey", ""),
        new User(UUID.randomUUID().toString(), "Caroline", ""))
        .forEach(userRepository::save);
    userRepository.findAll().forEach(System.out::println);
  }
}

As an alternative to UserRepoInitializer, we can add data.sql in resources folder and include insert statements in it.

INSERT INTO USER(USER_ID, FIRST_NAME, LAST_NAME) VALUES ('1','Mathew','Luis');
INSERT INTO USER(USER_ID, FIRST_NAME, LAST_NAME) VALUES ('2','Olive','Brenz');
INSERT INTO USER(USER_ID, FIRST_NAME, LAST_NAME) VALUES ('3','Joseph','Grand');
INSERT INTO USER(USER_ID, FIRST_NAME, LAST_NAME) VALUES ('4','David','Jr');
INSERT INTO USER(USER_ID, FIRST_NAME, LAST_NAME) VALUES ('5','Arvind','Kumar');

Run Spring boot application.

4

Access H2 database web console at  http://localhost:8080/h2-console
Web console prompts user to enter connection details;

JDBC URL: <what ever the value provided for spring.datasource.url in the application properties>
User Name: sa
Password:

Click on Connect

In the left side tree, make sure you see table USER

5

Now we have Spring Boot project with H2 Database running.

Thymeleaf

1

Let’s include Thymeleaf in the Spring Boot project by extending the User’s example, which we created under H2 Database section. We can use Thymeleaf to load Users from the database and show them on the HTML page.

Follow the steps mentioned under the H2 Database section and then include the below dependency to the project.

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

2

Create a new class called UserController in the project with the below content. This controller will listen for requests at /users endpoint and this will add all users from the database to the Model with the key ‘users’.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class UserController {
    @Autowired UserRepository userRepository;
    @GetMapping("/users")
    public String all(Model model) {
        model.addAttribute("users", userRepository.findAll());
        return "users";
    }
}

Create a Thymeleaf template file /src/main/resources/templates/users.html. In this file we will extract users and add them to a HTML table.

<html>
  <body>
  <h2>Users</h2>
    <table>
        <thead>
          <tr>
              <th>Id</th>
              <th>First Name</th>
              <th>Last Name</th>
          </tr>
        </thead>
        <tbody>
          <tr th:each="user: ${users}">
              <th th:text="${user.userId}"></th>
              <td th:text="${user.firstName}"></td>
              <td th:text="${user.lastName}"></td>
          </tr>
        </tbody>
    </table>
  </body>
</html>

Run Spring Boot application.

3

Access H2 database web console at  http://localhost:8080/h2-console and make sure you see User table.

Access application at  http://localhost:8080/users and we will see all Users in the page.

4

Now we have Spring Boot project with Thymeleaf running.

Spring Dev Tools

1

Create a new project by going to   start.spring.io and provide configuration details (Java version, Spring boot version) and choose Spring Boot DevTools and Thymeleaf as a dependency. (Note that we are including Web, just to demostrate dev tools). Download and open it in your Java editor.

You can also extend any existing Spring Boot application in your local by adding the below dependencies to that project.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <scope>runtime</scope>
    <optional>true</optional>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

Spring Dev Tools will use 35729 port number, so ensure no applications are using this port number.

2

Install LiveReload browser extension. Click  here for installation instructions. After the installation, start the LiveReload browser extension. This extension will look for a 35729 port on localhost and connects to it.

3

We need to do some configuration on the IntelliJ editor to do LiveReload work properly.

  • In File > Settings > Build, Execution, Deployment > Compiler > Enable ‘Build project automatically’
  • Go to Actions (Ctrl + Shift + A) and search for Registry. Look for ‘compiler.automake.allow.when.app.running’ and enable it.

Add below Java Class

@Controller
public class IndexController {
    @GetMapping("/")
    public String index() {
        return "index";
    }
}

In /src/main/resources/templates folder add index.html

<html>
  <body>
    <h2>Hello World!</h2>
  </body>
</html>

Run Spring boot application. In the startup logs, look for the line LiveReload server is running on port 35729. This is to make sure that the LiveReload server is up.

4

Enable LiveReload in the browser and access application at  http://localhost:8080

5

Now we have Spring Boot project with Dev Tools. Instead of restarting the application for every change, do a build, and it will trigger LiveReload on the browser to reload the page.

Mongo DB

1

Create a new project by going to   start.spring.io and provide configuration details (Java version, Spring boot version) and choose Spring Data MongoDB and Spring Web as a dependency. (Note that we are including Web to access MongoDB through REST endpoint). Download and open it in your Java editor.

You can also extend any existing Spring Boot application in your local by adding the below dependencies to that project.

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

Make sure you have MongoDB installed and running. If you like to setup MongoDB on the docker, then follow these  instructions.

2

Create Document class

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    @Id
    private String id;
    private String firstName;
    private String lastName;
}

I used Lombok annotations for less verbose. We are going to store and retrive User documents from MongoDB.

Create User Repository Interface

public interface UserRepository extends MongoRepository<User, String> {}

Create User REST controller

@RestController
public class UserController implements CommandLineRunner {
    @Autowired
    UserRepository userRepository;

    @Override
    public void run(String... args) throws Exception {
        userRepository.deleteAll();
        userRepository.save(new User(UUID.randomUUID().toString(), "Adam", "Jr"));
        userRepository.save(new User(UUID.randomUUID().toString(), "Olive", "Brown"));
        userRepository.save(new User(UUID.randomUUID().toString(), "Ana", "Smith"));
    }

    @GetMapping("/users")
    public List<User> all() {
        return userRepository.findAll();
    }
}

This class implements CommandLineRunner interface because this will help us to store some initial User records and this controller exposes a single end point at /users which will return all users.

3

Configure MongoDB in application.properties

spring.data.mongodb.authentication-database=admin
spring.data.mongodb.database=test_db
spring.data.mongodb.port=27017
spring.data.mongodb.host=localhost

Run Spring boot application.

4

Access /users endpoint to get all users.

curl http://localhost:8080/users

5

Now we have our Spring MongoDB running.



Each step starts with an action icon; this icon will give you an idea of what kind of work we will do in this step.

  • Terminal
  • Browser
  • Code editor
  • Info