스프링

 

 

스프링부트 AOP 처리  컨트롤에서 작동처리

 

 

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

 

import java.util.HashMap;
import java.util.Map;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import com.cos.photogramstart.handler.ex.CustomValidationApiException;

@Component
@Aspect
public class ValidationAdvice {

	//Controller.*(..) 모든 메소드
	@Around("execution(* com.cos.macaronics.web.api.*Controller.*(..))")
	public Object apiAdvice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {		
		System.out.println("web api 컨트롤러 ====== ");
		//proceedingJoinPoint => profile 함수의 모든 곳에 접근할 수 있는 변수
		//profile 함수보다 먼저 실행		
		
		Object[] args=proceedingJoinPoint.getArgs();
		for(Object arg:args) {
			if(arg instanceof BindingResult) {
				System.out.println("유효성을 검사하는 함수");
				BindingResult errors=(BindingResult)arg; 
				if(errors.hasErrors()) {
					Map<String,String> errorMap=new HashMap<>();
					
					for(FieldError error: errors.getFieldErrors()) {
						errorMap.put(error.getField(), error.getDefaultMessage());
					}
					
					throw new CustomValidationApiException("유효성 검사 실패함", errorMap);
				}
			}
		}
		return proceedingJoinPoint.proceed(); // profile 함수가 실행됨.
	}
	
	
	
	
	@Around("execution(* com.cos.macaronics.web.*Controller.*(..))")
	public Object advice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {		
		System.out.println("web 컨트롤러 ====== ");		
		return proceedingJoinPoint.proceed();
	}

	

}

 

 

 

컨트롤 예

/**
 * 댓글 삭제
 */
@RequiredArgsConstructor
@RestController
@Log4j2
public class CommentApiController {

	
	private final CommentService commentService;
	
	/**
	 * 댓글 등록
	 * @param commentDto
	 * @param principalDetails
	 * @return
	 */
	@PostMapping("/api/comment")
	public ResponseEntity<?> commentSave(@Valid @RequestBody CommentDto  commentDto, BindingResult bindingResult, @AuthenticationPrincipal PrincipalDetails principalDetails){			
		
		commentDto.setUser(principalDetails.getUser());
		CommentResDTO commentResDTO=  commentService.댓글쓰기(commentDto);
		return ResponseEntity.ok().body(new CMRespDto<>(1,"댓글 등록 성공", commentResDTO));
	}
	

 

 

 

소스 :

https://github.com/braverokmc79/EaszUp-Springboot-Photogram-Start

 

 

 

about author

PHRASE

Level 60  라이트

토끼를 다 잡으면 사냥개를 잡는다 , 요긴한 때는 소중히 여기다가도 필요가 없게 되면 쉽게 천대하고 버림을 비유하는 말.

댓글 ( 4)

댓글 남기기

작성

스프링 목록    more