Declaring an Aspect

2024. 11. 17. 12:11Spring Framework/Aspect Oriented Programming with Spring

@AspectJ 지원이 활성화된 상태에서, 애플리케이션 컨텍스트에 정의된 빈 중, 클래스에 @Aspect 애노테이션이 있는 @AspectJ aspect은 Spring에 의해 자동으로 감지되며 Spring AOP를 구성하는 데 사용됩니다. 다음 두 가지 예시는 크게 유용하지 않은 aspect를 정의하는 데 필요한 최소 단계를 보여줍니다.

첫 번째 예시에서는 애플리케이션 컨텍스트에 있는 일반적인 빈 정의가 @Aspect 애노테이션이 있는 빈 클래스를 가리키는 방법을 보여줍니다:

<bean id="myAspect" class="com.xyz.NotVeryUsefulAspect">
    <!-- 여기에서 측면의 속성을 구성 -->
</bean>

 

두 번째 예시에서는 @Aspect 애노테이션이 달린 NotVeryUsefulAspect 클래스 정의를 보여줍니다:

package com.xyz;

import org.aspectj.lang.annotation.Aspect;

@Aspect
public class NotVeryUsefulAspect {
}

@Aspect로 애노테이션된 Aspect 클래스는 다른 클래스와 마찬가지로 메서드와 필드를 가질 수 있으며, 포인트컷, 어드바이스, 그리고 Introduction(인터타입) 선언을 포함할 수 있습니다.

package com.example.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class LoggingAspect {

    @Before("execution(* com.example.service.MyService.*(..))")
    public void logBeforeMethod(JoinPoint joinPoint) {
        System.out.println("[📌 Before Advice] 메서드 호출 전: " + joinPoint.getSignature().getName());
    }
}

위 코드 분석:

  • @Aspect : 이 어노테이션이 달린 클래스는 AspectJ의 aspect 클래스임을 선언.
  • @Before : 이 어노테이션은 어드바이스의 한 종류를 나타내고 이 어노테이션의 vaule 속성 값은 포인트컷.
  • logBeforeMethod : LoggingAspect 클래스의 Cross-Cutting Concern.

 

Note

Autodetecting aspects through component scanning

classpath 스캔을 통해 Spring이 aspect 클래스를 자동으로 감지하도록 하거나, Spring XML 설정에서 일반 빈으로 등록하거나, @Configuration 클래스의 @Bean 메서드를 통해 등록할 수 있습니다. 그러나 @Aspect 애노테이션만으로는 클래스패스에서 자동 감지가 충분하위지 않습니다. 이 경우에는 @Component 애노테이션(또는 Spring의 컴포넌트 스캐너 규칙에 따라 자격이 있는 사용자 정의 스테레오타입 애노테이션)을 추가해야 합니다.

 

 

Advising aspects with other aspects?
Spring AOP에서 aspect 자체는 다른 aspect의 어드바이스 대상이 될 수 없습니다. 클래스에 @Aspect 애노테이션이 붙으면 해당 클래스는 aspect로 표시되며, 따라서 auto-proxying 대상에서 제외됩니다.

'Spring Framework > Aspect Oriented Programming with Spring' 카테고리의 다른 글

Introductions  (1) 2024.11.17
Declaring a Pointcut  (0) 2024.11.17
Enabling @AspectJ Support  (0) 2024.11.17
Spring instrument  (0) 2024.11.17
Programmatic Creation of @AspectJ Proxies  (0) 2024.11.15