Validation 디펜던시 적용
/pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
Entity
@NotBlank 적용
@Entity
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long departmentId;
// not blank 적용
@NotBlank(message = "Please Add Department Name")
private String departmentName;
private String departmentAddress;
private String departmentCode;
...
}
Controller
@Valid 적용
@RestController
public class DepartmentController {
@Autowired
private DepartmentService departmentService;
@PostMapping("/departments")
public Department saveDepartment(@Valid @RequestBody Department department) {
return departmentService.saveDepartment(department);
}
}
Logger 적용
@RestController
public class DepartmentController {
@Autowired
private DepartmentService departmentService;
private final Logger LOGGER =
LoggerFactory.getLogger(DepartmentController.class);
@PostMapping("/departments")
public Department saveDepartment(@Valid @RequestBody Department department) {
LOGGER.info("Inside saveDepartment of DepartmentController");
return departmentService.saveDepartment(department);
}
}
결과
Lombok이란 어노테이션 기반으로 코드를 자동완성 해주는 라이브러리이다. Lombok을 이용하면 Getter, Setter, Equlas, ToString 등과 다양한 방면의 코드를 자동완성 시킬 수 있다.
Lombok 디펜던시 및 적용
/pom.xml
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<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>
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long departmentId;
@NotBlank(message = "Please Add Department Name")
private String departmentName;
private String departmentAddress;
private String departmentCode;
}
폴더 구조
1) DepartmentNotFoundException 생성
public class DepartmentNotFoundException extends Exception{
public DepartmentNotFoundException() {
super();
}
public DepartmentNotFoundException(String message) {
super(message);
}
public DepartmentNotFoundException(String message, Throwable cause) {
super(message, cause);
}
public DepartmentNotFoundException(Throwable cause) {
super(cause);
}
protected DepartmentNotFoundException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
2) ErrorMessage 생성 (lombok 적용)
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ErrorMessage {
private HttpStatus status;
private String message;
}
3) RestResponseEntityExceptionHandler 생성
@ControllerAdvice
@ResponseStatus
public class RestResponseEntityExceptionHandler
extends ResponseEntityExceptionHandler {
@ExceptionHandler(DepartmentNotFoundException.class)
public ResponseEntity<ErrorMessage> departmentNotFoundException(DepartmentNotFoundException exception,
WebRequest request) {
ErrorMessage message = new ErrorMessage(HttpStatus.NOT_FOUND,
exception.getMessage());
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(message);
}
}
(1) @ControllerAdvice : @Controller나 @RestController에서 발생한 예외를 한 곳에서 관리하고 처리할 수 있게 도와주는 어노테이션이다.
(2) @ResponseStatus : @ResponseStatus에 어노테이션을 부여하고 value에 상태 코드를 지정하면, 그 응답의 상태 코드를 지정할 수 있다.
(3) @ExceptionHandler : @ExceptionHandler같은 경우는 @Controller, @RestController가 적용된 Bean내에서 발생하는 예외를 잡아서 하나의 메서드에서 처리해주는 기능을 한다.
4) Service 적용
@Service
public class DepartmentServiceImpl implements DepartmentService {
@Autowired
private DepartmentRepository departmentRepository;
@Override
public Department fetchDepartmentById(Long departmentId) throws DepartmentNotFoundException {
Optional<Department> department = departmentRepository.findById(departmentId);
if(!department.isPresent()) {
throw new DepartmentNotFoundException("Department Not Available");
}
return department.get();
}
}
5) 결과
1) application.properties 파일 MySql 설정
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/dcbapp
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name =com.mysql.jdbc.Driver
spring.jpa.show-sql: true
2) Mysql 디펜던시 추가
<dependency>
<groupId> mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
참고 : Spring Boot Tutorial | Full In-depth Course - Daily Code Buffer