スプリングAOP:@AOP


1.Spring AOP設定コード


PerfAspect.java
@Component
@Aspect
public class PerfAspect {

    // logPerf 함수 : AOP의 advice(해야 할 일)에 해당함.
    // pjp : advice가 적용되는 대상 (Ex: createEvent, publishEvent)
    // @Around : advice를 어떻게 적용할 것인가. 메서드를 감싸는형태로 적용됨, 메서드 호출 이전 이후 Exception 시에도 특정한 일을 할 수 있다.
    // @Around("execution(* me.hyunki..*.EventService.*(..))") -> EventService 안에 있는 모든 메서드에 아래의 행위를 적용 하라는 뜻 (PointCut을 정의함)
    // @Around("bean(simpleEventService)") : bean을 사용 -> 해당 bean의 모든 메서드에 적용되어 버리는 단점
    @Around("@annotation(PerfLogging)") // deleteEvent에는 적용하고 싶지 않기 때문에 어노테이션이 있는 곳에만 실행 되게끔 설정함. (이게 가장 유용함)
    //원본 코드에 수정이나 추가 없이 많은 클래스에 아래의 행위를 끼워 넣을수 있다.
    public Object logPerf(ProceedingJoinPoint pjp) throws Throwable{
        long begin = System.currentTimeMillis();
        Object retVal = pjp.proceed(); //메서드 실행
        System.out.println(System.currentTimeMillis() - begin);
        return retVal;
    }

    //모든 메서드 실행 이전에 hello가 찍힘
    @Before("bean(simpleEventService)")
    public void hello() {
        System.out.println("hello");
    }
}
PerfLogging.java
/**
 * 이 에노테이션을 사용하면 성능을 로깅해 줍니다.
 */

@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.CLASS) //기본 값이 클래스
public @interface PerfLogging {
}
EventService.java
public interface EventService {

    void createEvent();

    void publishEvent();

    void deleteEvent();
}
SimpleEventService.java
@Service
public class SimpleEventService implements EventService{

    @PerfLogging
    @Override
    public void createEvent() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Created an event");
    }

    @PerfLogging
    @Override
    public void publishEvent() {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Published an event");
    }

    public void deleteEvent() {
        System.out.println("Delete an event");
    }
}
AppRunner.java
@Component
public class AppRunner implements ApplicationRunner {

    @Autowired
    EventService eventService; // Interface가 있는 경우에는 Interface다 타입으로 주입 받는게 가장 좋음

    @Override
    public void run(ApplicationArguments args) throws Exception {
        eventService.createEvent();
        eventService.publishEvent();
        eventService.deleteEvent();
    }
}
  • AOPが適用される場合、IDEはAOPに関連するタグを表示する.
  • PerfLogging.最良の方法はjavaで直接注釈を作成し、その注釈の部分にのみ適用することです.
  • 2.授業ノート


    動画ベーススプリング@AOP
    依存項目の追加
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>
    属性の定義
  • @Aspect
  • 空(コンポーネントスキャンを使用する場合)に登録する必要があるため、@コンポーネントも追加します.
  • ポイントカットの定義
  • @PointCut(式)
  • 主な式
  • execution
  • @annotation
  • bean
  • 点カットセット
  • &&,||, !
  • アドレスの定義
  • @Before
  • @AfterReturning
  • @AfterThrowing
  • @Around
  • リファレンス
  • https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#aop-pointcuts