Spring Boot) AOP

메타플랫폼대표
|2024. 8. 13. 10:58
반응형

AOP 작업 - 로깅작업(프로세서 실행 일자), 보안 작업(미인증 유저 진입불가), Transaction(트랜잭션) - 예외 발생시 Method 전체 실행 멈춤

 

 

[ 기존 Spring FramWork에서의 AOP 적용 ]

 

- 이렇게 한 번에 @transactional을 거는 것보다 필요한 Method에 거는것이 낫다

 

 

 

 


 

 

[ AOP인지 아닌지 인식하는것 ]

@Aspect Annotation을 지정해준뒤,

아래에 @Pointcut에서 지정한 위치를 보면 Service package안에 있는 Service라는 이름이 있으면, 감시 설정이 발동한다.

 

 

 

추가하기

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

 

 

Service 생성하기

 

 

TestServiceImpl 생성하기

package com.githrd.demo_aop.service;

import org.springframework.stereotype.Service;

@Service
public class TestServiceImpl implements TestService {

    @Override
    public String hello() {

        try {
            Thread.sleep(1234);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return "Hello Everyone!!";
    }

    @Override
    public String hi() {

        return "Hi~~ Thank you!!";
    }
}

 

 

 

Advice 추가하기

package com.githrd.demo_aop.advice;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import jakarta.servlet.http.HttpServletRequest;

@Aspect
@Component
public class Advice {

    //Spring에게 Injection시켜달라고 요청
    @Autowired
    HttpServletRequest request;

    // Target(감시지점) 설정
    //   *(..) : 모든메소드(.. <-인자구분없다)
    @Pointcut("execution(* com.githrd.demo_aop.service.*Service.*(..))")
    public void service_pointcut(){}


   
    @Before("service_pointcut()")
    public void before(JoinPoint jp){

        Signature s = jp.getSignature();
        System.out.println("--Before : "  + s.toShortString());

        long start = System.currentTimeMillis();
        //request binding 
        request.setAttribute("start", start);

    }

    @After("service_pointcut()")
    public void after(JoinPoint jp){

        Signature s = jp.getSignature();
        System.out.println("--After : "  + s.toShortString());


        long start = (Long)request.getAttribute("start");

        long end = System.currentTimeMillis();


        System.out.printf("--[수행시간] : %d(ms)\n", end - start);

    }
}

 

 

 

Main에 Annotation 추가하기

@EnableAspectJAutoProxy(proxyTargetClass = true)
@SpringBootApplication
public class DemoAopApplication {

	public static void main(String[] args) {
		SpringApplication.run(DemoAopApplication.class, args);
	}

}

 

 

 

TestController 추가하기

@RestController
public class TestController {

    @Autowired
    TestService testService;

    @GetMapping("/hello") // Rest API에서는 명사형으로 uri 요청
    public String hello() {

        return testService.hello();
    }

    @GetMapping("/hi") // Rest API에서는 명사형으로 uri 요청
    public String hi() {

        return testService.hi();
    }


}

 

 

 

 

반응형

'SpringBoot↗' 카테고리의 다른 글

Spring Boot)File Upload 파일업로드  (0) 2024.08.13
Spring Boot)Interceptor  (0) 2024.08.13
AWS 서버(프로젝트 업로드)  (0) 2024.08.13
Spring Boot)Transaction  (0) 2024.08.12
Spring Boot)JPA로 Sawon 데이터 활용하기  (0) 2024.08.12