spring initializrでプロジェクトを作成する
Maven
3.2.5
Group: com.codingshuffle
Artifact: tutorial
Name : Anuj
Description: Demo project for Spring Boot for Anuj
Package name: com.example
jar
Java 22
lombok
Spring Web
H2 Database
フォルダとファイルを作成する
(1)src/java/com/codingshuffle/tutorialにProdDBファイルを作成する
package com.codingshuffle.tutorial;
public class ProdDB implements DB {
public String getData() {
return "Prod Data";
}
}
(2)src/java/com/codingshuffle/tutorial/AnujApplicationファイルを編集する
package com.codingshuffle.tutorial;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class AnujApplication implements CommandLineRunner {
@Autowired
DB db;
public static void main(String[] args) {
SpringApplication.run(AnujApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
System.out.println(db.getData());
}
}
(3)src/java/com/codingshuffle/tutorialにDevDBファイルを作成する
package com.codingshuffle.tutorial;
public class DevDB implements DB {
public String getData() {
return "Dev Data";
}
}
(4)src/java/com/codingshuffle/tutorialにDBファイルを作成する
package com.codingshuffle.tutorial;
public interface DB {
public String getData();
default String getDefaultData() {
return "Default DB Data";
}
}
(5)src/java/com/codingshuffle/tutorialにconfigurationフォルダと
AppConfigファイルを作成する
package com.codingshuffle.tutorial.configuration;
import com.codingshuffle.tutorial.DB;
import com.codingshuffle.tutorial.DevDB;
import com.codingshuffle.tutorial.ProdDB;
import org.springframework.context.annotation.Bean;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
@Configurable
public class AppConfig {
@Bean
@ConditionalOnProperty(name = "project.name", havingValue = "development")
public DB getDevDBBean() {
return new DevDB();
}
@Bean
@ConditionalOnProperty(name = "project.name", havingValue = "production")
public DB getProdDBBean() {
return new ProdDB();
}
@Bean
public ModelMapper getModelMapper() {
return new ModelMapper();
}
}
(6)resources/application.properties を編集する
spring.application.name=Anuj
project.mode=production
spring.h2.console.enabled=true
server.port=9000
(7)src/java/com/codingshuffle/tutorialにcontrollerフォルダと
EmployeeControllerファイルを作成する
package com.codingshuffle.tutorial.controller;
//Operation
//GET /employees
//POST /employees
//DELETE /employees/{id}
import com.codingshuffle.tutorial.dto.EmployeeDTO;
import com.codingshuffle.tutorial.service.EmployeeService;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping(path = "/employees")
public class EmployeeController {
private final EmployeeService employeeService;
public EmployeeController(EmployeeService employeeService) {
this.employeeService = employeeService;
}
@GetMapping
public List<EmployeeDTO> getAllEmployee() {
return employeeService.getAllEmployees();
}
@GetMapping(path = "/{id}")
public EmployeeDTO getEmployeeById(@PathVariable("id") Long employeeId) {
return employeeService.getEmployeeById(employeeId);
}
@PostMapping
public EmployeeDTO createNewEmployee(@RequestBody EmployeeDTO employeeDTO) {
return employeeService.createNewEmployee(employeeDTO);
}
@DeleteMapping(path = "/{id}")
public boolean deleteEmployeeById(@PathVariable Long id) {
return employeeService.deleteEmployeeById(id);
}
}
(8)src/java/com/codingshuffle/tutorialにdtoフォルダとEmployeeDTOファイルを作成する
package com.codingshuffle.tutorial.dto;
import com.fasterxml.jackson.annotation.JacksonProperty;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDate;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class EmployeeDTO {
private Long id;
private String name;
private LocalDate dateOfJoining;
@JsonProperty("isActive")
private boolean isActive;
}
(9)src/java/com/codingshuffle/tutorialにentitiesフォルダとEmployeeEntityファイルを作成する
package com.codingshuffle.tutorial.entities;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDate;
@Entity
@Table(name = "employees")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class EmployeeEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private LocalDate dateOfJoining;
private boolean isActive;
}
(10)src/java/com/codingshuffle/tutorialにrepositoriesフォルダとEmployeeRepositoryファイルを作成する
package com.codingshuffle.tutorial.repositories;
import com.codingshuffle.tutorial.entities.EmployeeEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface EmployeeRepository extends JpaRepository<EmployeeEntity, Long> {
}
(11)src/java/com/codingshuffle/tutorialにserviceフォルダとEmployeeServiceファイルを作成する
package com.codingshuffle.tutorial.service;
import com.codingshuffle.tutorial.dto.EmployeeDTO;
import com.codingshuffle.tutorial.entities.EmployeeEntity;
import com.codingshuffle.tutorial.repositories.EmployeeRepository;
import java.util.List;
import java.util.stream.Collectors;
import org.modelmapper.ModelMapper;
import org.springframework.stereotype.Service;
@Service
public class EmployeeService {
final EmployeeRepository employeeRepository;
final ModelMapper modelMapper;
public EmployeeService(EmployeeRepository employeeRepository, ModelMapper modelMapper) {
this.employeeRepository = employeeRepository;
this.modelMapper = modelMapper;
}
public EmployeeDTO getEmployeeById(Long id) {
EmployeeEntity employeeEntity = employeeRepository.getById(id);
return modelMapper.map(employeeEntity, EmployeeDTO.class);
}
public EmployeeDTO createNewEmployee(EmployeeDTO employeeDTO) {
EmployeeEntity employeeEntity = modelMapper.map(employeeDTO, EmployeeEntity.class);
return modelMapper.map(employeeRepository.save(employeeEntity), EmployeeDTO.class);
}
public List<EmployeeDTO> getAllEmployee() {
return employeeRepository
.findAll()
.stream()
.map(employeeEntity -> modelMapper.map(employeeEntity, EmployeeDTO.class))
.collect(Collectors.toList());
}
public boolean deleteEmployeeById(Long id) {
boolean isPresent = employeeRepository.existsById(id);
if (!isPresent)
return false;
employeeRepository.deleteById(id);
return true;
}
}
(12)pom.xmlを編集する
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.codingshuffle</groupId>
<artifactId>tutorial</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Anuj</name>
<description>Demo project for Spring Boot for Anuj</description>
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<properties>
<java.version>22</java.version>
</properties>
<dependencies>
<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>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
参考サイト
Build REST APIs in Spring Boot as a Complete Beginner | 2 Hrs Crash Course | Bootcamp