본문 바로가기

프로그래밍/Spring Boot

Spring Boot_AOP 관점 지향 프로그래밍

반응형

AOP 관점 지향 프로그래밍

: AOP(Aspect-Oriented Programming)는 OOP(Object-Oriented Programming)의 보완적인 개념이다.
프로그램을 구성하는 여러 모듈에서 공통적으로 사용하는 코드를 분리하여 재사용성과 유지 보수성을 향상 시키는 프로그래밍 기법이다.
→ 핵심 코드와 부가적인 코드(ex> 방어적 코드) 분리
 
AOP는 Aspect와 Advice를 사용하여 구현하며, @Aspect 어노테이션과 @Before, @After, @Pointcut 등의 어노테이션을 사용하여 정의한다. 
→ @Before 메서드 수행 전, @After 메서드 수행 후, @Pointcut 관심 조인 포인트를 결정하므로 실행되는 시기를 제어할 수 있음.
 
 

UserDTO.java

1
2
3
4
5
6
7
8
9
10
11
package com.example.demo4.dto;
 
import lombok.Data;
 
@Data
public class UserDTO {
    
    private String name;
    private Integer age;
    
}
cs

RestApiController.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@RestController
@RequestMapping("/api")
public class RestApiController {
    
    @GetMapping("/get/{id}")
    public void get(@PathVariable long id) {
        System.out.println("method : get");
        System.out.println("method : id" + id);
    }
    
    @PostMapping("/post")
    public ResponseEntity<UserDTO> post(@RequestBOdy UserDTO user) {
        System.out.println("method : post");
        System.out.println("method : user" + user.toString());
        return ResponseEntity.status(HttpStatus.OK).body(user);
    }
}
cs

AopParameter.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
@Aspect
@Component // IoC의 관리 대상이 된다.
public class AopParameter {
    
    //포인트 컷
    //execution 표현식 : com.example.demo4.controller 아래에 있는 모든 파일을 적용
    @Pointcut("execution(* com.example.demo4.controller..*.*(..))")
    private void cut() {
    
    }
    
    // cut() 메서드가 실행되는 지점 이전에 before() 메서드 실행
    @Before("cut()")
    public void before(JoinPoint joinPoint) {
        // controller에 있는 /api/get 호출하기 전에 수행
        System.out.println("before 수행");
        
        // 어떤 메서드가 동작되었는지 확인할 수 있는 메서드 MethodSignature
        MethodSignature methodSignature = (MethodSignature)joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        // System.out.println("사용된 메서드 확인 : " + method.getName());
        
        // JoinPoint : 메소드의 정보를 보여줌
        Object[] args = joinPoint.getArgs();
        
        for(Object obj : args) {
            System.out.pritnln("type : " + obj.getClass().getSimpleName());
            System.out.println("value : " + obj);
        }
    }
    
    @AfterReturning(value = "cut()", returning = "obj")
    public void afterReturn(JoinPoint joinPoint, Object obj) {
        System.out.println("---------");
        System.out.println("return obj");
        System.out.println("obj : " + obj);
    }
}
cs

콘솔 화면

http://localhost:8080/api/get/100

 

http://localhost:8080/api/post

 

반응형