Spring Boot basic annotations
- @Bean - indicates that a method produces a bean to be managed by Spring.
- @Service - indicates that an annotated class is a service class.
- @Repository - indicates that an annotated class is a repository, which is an abstraction of data access and storage.
- @Configuration - indicates that a class is a configuration class that may contain bean definitions.
- @Controller - marks the class as web controller, capable of handling the requests.
- @RequestMapping - maps HTTP request with a path to a controller method.
- @Autowired - marks a constructor, field, or setter method to be autowired by Spring dependency injection.
- @SpringBootApplication - enables Spring Boot autoconfiguration and component scanning.
There are also Hibernate @Entity, @Table, @Id, and @GeneratedValue annotations in the example.
Spring Boot basic annotations example
The following application is a Spring Boot application which returns data from an H2 database using Spring Data JPA. The application uses FreeMarker as a template engine.Tools and Technologies used
- Spring Boot 2+
- Maven 3+
- STS or Eclipse IDE
- Freemarker
- JDK 8+ or OpenJDK 8+
- H2 Database
- Hibernate - 5.2.17.Final
1. Create a Spring Boot Application
2. Maven Dependencies
<?xml version="1.0" encoding="UTF-8"?>
<project
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>net.guides.springboot2</groupId>
<artifactId>springboot2-freemarker-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot2-freemarker-example</name>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
<relativePath />
<!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
3. Project Structure
4. JPA Entity - Employee.java
package net.guides.springboot2.freemarker.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "employees")
public class Employee {
private long id;
private String firstName;
private String lastName;
private String emailId;
public Employee() {
}
public Employee(String firstName, String lastName, String emailId) {
this.firstName = firstName;
this.lastName = lastName;
this.emailId = emailId;
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
@Column(name = "first_name", nullable = false)
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
@Column(name = "last_name", nullable = false)
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Column(name = "email_address", nullable = false)
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
@Override
public String toString() {
return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", emailId=" + emailId +
"]";
}
}
5. JPA Repository - EmployeeRepository.java
The @Repository annotation is used to define a repository:package net.guides.springboot2.freemarker.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import net.guides.springboot2.freemarker.model.Employee;
@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long>{
}
6. Service Layer
EmployeeService.java
package net.guides.springboot2.freemarker.service;
import java.util.List;
import java.util.Optional;
import net.guides.springboot2.freemarker.model.Employee;
public interface EmployeeService {
List < Employee > findAll();
void save(Employee employee);
Optional < Employee > findById(Long id);
void delete(long id);
}
EmployeeServiceImpl.java
package net.guides.springboot2.freemarker.service;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import net.guides.springboot2.freemarker.model.Employee;
import net.guides.springboot2.freemarker.repository.EmployeeRepository;
@Service
public class EmployeeServiceImpl implements EmployeeService {
@Autowired
private EmployeeRepository employeeRepository;
@Override
public Optional < Employee > findById(Long id) {
return employeeRepository.findById(id);
}
@Override
public void save(Employee employee) {
employeeRepository.save(employee);
}
@Override
public List < Employee > findAll() {
return employeeRepository.findAll();
}
@Override
public void delete(long id) {
employeeRepository.deleteById(id);
}
}
7. Define Spring Controller - EmployeeController.java
package net.guides.springboot2.freemarker.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;
import net.guides.springboot2.freemarker.model.Employee;
import net.guides.springboot2.freemarker.service.EmployeeService;
@Controller
public class EmployeeController {
@Autowired
private EmployeeService employeeRepository;
@GetMapping("/")
public String index(Model model) {
return "index";
}
@GetMapping("/showEmployees")
public ModelAndView showCities() {
List <Employee> employees = employeeRepository.findAll();
Map <String, Object> params = new HashMap <String, Object> ();
params.put("employees", employees);
return new ModelAndView("showEmployees", params);
}
}
application.properties
spring.freemarker.template-loader-path: classpath:/templates
spring.freemarker.suffix: .ftl
8. Define View Templates
index.ftl
<!DOCTYPE html>
<html>
<head>
<title>Home page</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="panel panel-primary">
<div class="panel-heading">
<h2>Home Page</h2>
</div>
<a href="showEmployees">Show Employees (Retrieve employee data from database)</a>
</div>
</div>
</body>
</html>
showEmployees.ftl
<!DOCTYPE html>
<html>
<head>
<title>Employee List</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
crossorigin="anonymous">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="container">
<div class="panel panel-primary">
<div class="panel-heading">
<h2>Employee List</h2>
</div>
<div class="panel-body">
<table class="table table-striped">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<#list employees as employee>
<tr>
<td>${employee.firstName}</td>
<td>${employee.lastName}</td>
<td>${employee.emailId}</td>
</tr>
</#list>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
9. Run Application
package net.guides.springboot2.freemarker;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import net.guides.springboot2.freemarker.model.Employee;
import net.guides.springboot2.freemarker.repository.EmployeeRepository;
@SpringBootApplication
public class Application implements CommandLineRunner {
@Autowired
private EmployeeRepository employeeRepository;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
public void run(String...args) throws Exception {
employeeRepository.save(new Employee("Ramesh", "Fadatare", "ramesh@gmail.com"));
employeeRepository.save(new Employee("Tom", "Cruise", "tom@gmail.com"));
employeeRepository.save(new Employee("John", "Cena", "john@gmail.com"));
employeeRepository.save(new Employee("tony", "stark", "stark@gmail.com"));
// get list of employees
List < Employee > employees = employeeRepository.findAll();
employees.forEach(employee - > System.out.println(employee.toString()));
}
}
10. Demo
Get source code of this tutorial on my GitHub Repository.
Continue Learning with Java Guides
Want to take your programming skills to the next level? Explore my practical Udemy courses on Java, Spring Boot, Microservices, Full-Stack Development, Docker, and Generative AI. You can also follow my structured learning roadmaps to become a professional developer.
By Ramesh Fadatare - Udemy Instructor Partner
Comments
Post a Comment
Leave Comment