Spring Boot is an open-source java framework that provides a comprehensive set of tools and libraries that make it easy for us to carry out the development and deployment of spring applications. Spring Boot has some key features which include Auto-configuration, embedded web server, and production-ready features and is easy to carry out testing. it provides an efficient and fast way to develop spring applications with minimal configuration and is most loved because of the ease of use.
We are building the Spring applications from scratch following the guide below:-
Step 1: Install Java and an IDE
We will recommend you download and install the latest java version from oracle’s official website
To begin with, you need to have Java installed on your machine. You can download and install the latest version of Java from the official Oracle website and then download an IDE, we mostly recommend IntelliJ IDEA, Eclipse, and NetBeans, for our Demo we will use IntelliJ.
Step 2: Create a new Spring Boot project
to create the spring Boot project using IntelliJ we follow these steps:
- Open IntelliJ IDEA.
- Click on “Create New Project”.
- Select “Spring Initializr” and click “Next”.
- Give your project a name, choose a location, and select a Java version.
- Select “Spring Web” and “Spring Boot DevTools” as dependencies. You can also add other dependencies based on your project requirements.
- Click “Next” and then “Finish” to create your project.
Step 3: Create a REST controller
The Spring Boot Project is now created what follows is to create a REST controller to handle HTTP requests following the guide below
- In the Project tool window, navigate to “src/main/java” and right-click on the package where you want to create your controller.
- Select “New” and then “Java Class”.
- Give your controller a name and select “RestController” as the class type.
- Add a request mapping to your controller by adding the below code which will handle GET request to the “/hello” endpoint so as to return the String “Hello World!”
@RestController
public class MyController {
@GetMapping("/hello")
public String hello() {
return "Hello, World!";
}
}
Step 4: Run the application
We will now proceed and run the Spring Boot application and test the REST controller,to be in a position to run the application here are the steps
- Click on the green arrow icon in the toolbar to run your application.
- Wait for your application to start up. You should see log messages in the console.
- Open a web browser and navigate to “http://localhost:8080/hello“.
- You should see the message “Hello, World!” displayed in your browser.
You Just Built a Spring Boot Application and now we can proceed to build the package and deploy the application.
Step 5: Build and package your application
for us to deploy we can build a JAR file using maven by following the below steps
- In the terminal, navigate to your project’s root directory.
- Run the command “mvn clean package”. This will compile your application and create a JAR file in the “target” directory.
- You can now deploy your JAR file to a server or cloud platform of your choice. we can even dockerize and deploy in Kubernetes or open shift environment
Spring Boot Integration to a Database
Step 1: Add database dependencies
To connect the Spring Boot application to a database we need to add the appropriate database dependencies to the project, which is added in the projects pom.xml file. an example is The dependencies below that provide the necessary JPA and JDBC components for connecting to a MySQL database.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
Step 2: Configure database properties
application.properties
the file needs to be configured with the needed properties for the case of connecting to MySQL we add the below properties, which specify the database URL, Username, and password and hibernate DDL(Data Definition Language) auto-generated mode
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=mypassword
spring.jpa.hibernate.ddl-auto=create
Step 3: Create an entity
For us to interact with the database an entity class that maps to a database table needs to be created, example a database for users having id, name, and emails columns we will create the entity class table as below where this class uses JPA annotation to map the id, name, email properties to the matching database columns.
@Entity
@Table(name = "customer")
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
// getters and setters
}
Step 4: Create a repository
a repository interface that extends JpaRepository
is required so as to perform (Create, Read, Update, Delete) CRUD operations on the database as listed in the below example and it inherits the method performing CRUD operations from JpaRepository
@Repository
public interface CustomerRepository extends JpaRepository<Customer, Long> { }
Step 5: Use the repository
Proceed to use the repository to interact with the database in the controller 0r service classes. suppose we have UserService class to get all the Users from the database using the findAll()
the method as shown below.
@Service
public class UserService {
@Autowired
private UserRepository UserRepository;
public List<User> getAllCustomers() {
return UserRepository.findAll();
}
}
Step 6: Enable JPA auditing (optional)
when JPA is added to the main application class it allows tracking of audit information for the entities’ creation and modification timestamps. the annotation enables JPA auditing and sets up the needed infrastructure to automatically populate audit fields.
@EnableJpaAuditing
@SpringBootApplication
public class MyApp {
// ...
}
Step 7: Use named queries (optional)
we can define named queries by adding @NamedQuery
annotation to an entity class, this allows us to use custom queries in the repository.
@Entity
@Table(name = "customer")
@NamedQuery(name = "Customer.findByName", query = "SELECT c FROM Customer c WHERE c.name = ?1")
public class Customer {
// ...
}
This named query defines a custom query to find Users by name. You can then use this named query in your repository. The repository method below uses @NamedQuery
annotation to execute the custom query defined in our User entity class
@Repository
public interface CustomerRepository extends JpaRepository<Customer, Long> {
List<Customer> findByName(String name);
}
Step 8: Use transactions
By default, all methods in a Spring Boot repository are executed within a transaction, to customize transaction behavior like different propagation levels or isolation levels, we can annotate the service method using @Transactional
as shown in the example below
@Service
public class UserService {
@Autowired
private UserRepository UserRepository;
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
public Customer createUser(User user) {
return UserRepository.save(user);
}
}
This service method will now be executed within a transaction with the specified propagation and isolation levels.
Conclusion
Spring Boot is a powerful Java framework that simplifies the development and deployment of Spring-based applications. Its features like auto-configuration, embedded web server, and production-ready features make it an ideal choice for developers who want to create robust and scalable applications with minimal configuration and boilerplate code.
Spring Boot’s integration with other Spring projects like Spring Data and Spring Security makes it easy to build complex applications that require these technologies. Its easy-to-use testing framework allows developers to test their applications using a variety of testing frameworks like JUnit and Mockito.
Overall, Spring Boot is a popular choice for enterprise and web development due to its simplicity and ease of use, making it an excellent choice for developers who want to create high-quality applications quickly and efficiently.
Related Content
Leave a Reply