본문 바로가기

Web/spring

[Spring framework Core] 5. Aspect Oriented Programming with Spring (1)

728x90

https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#aop

 

Core Technologies

In the preceding scenario, using @Autowired works well and provides the desired modularity, but determining exactly where the autowired bean definitions are declared is still somewhat ambiguous. For example, as a developer looking at ServiceConfig, how do

docs.spring.io

 

틀린 해석이나 내용이 있다면 알려주세요, 감사합니다 😶‍🌫️

 


5.1. AOP Concepts ~ 5.4.3. Declaring a Pointcut 

 

If you are interested only in generic declarative services or other pre-packaged declarative middleware services such as pooling, you do not need to work directly with Spring AOP, and can skip most of this chapter.

 

일반적인 middleware service 에서는 직접 AOP를 작업할 필요가 없기 때문에 대부분을 건너뛰라고 한다

하지만 나는 궁금하니까 개념을 알아보고 싶어서 정리해본다

 

 

 

 

 

5. Aspect Oriented Programming with Spring

Aspect-oriented Programming (AOP) 는 객체 지향 프로그래밍(OOP)를 보완하는 다른 사고 방식의 프로그램 구조이다

OOP에서 모듈화의 핵심단위가 클래스라면, AOP에서 모듈 단위는 Aspect 이다

Aspect는 여러 유형과 객체를 가로지르는 문제(트랜잭션 관리)의 모듈화를 가능하게 한다 (crosscutting)

 

Spring의 주요 구성 요소 중 하나는 이 AOP 프레임워크이다

Spring IoC 컨테이너는 AOP에 의존하지는 않지만 AOP는 Spring IoC를 보완하는 middleware Solution을 제공한다

 

Spring AOP with AspectJ pointcuts 

Spring provides simple and powerful ways of writing custom aspects by using either a schema-based approach or the @AspectJ annotation style. Both of these styles offer fully typed advice and use of the AspectJ pointcut language while still using Spring AOP for weaving.

 

스프링은 스키마 기반 접근 방식 또는 @AspectJ 애노테이션 스타일을 사용하여 간단히 사용한다

 

 

AOP는 이럴 때 사용된다

  • Provide declarative enterprise services. 선언적 트랜잭션 관리
  • Let users implement custom aspects, complementing their use of OOP with AOP. OOP 보완

 

 

 

5.1. AOP Concepts

AOP 라는 용어는 Spring 에서만 쓰이지않는다, 직관적인 단어도 아니다. 그래서 혼란스러울 것이라고 한다.
개념을 정의해보자면
 
  • Aspect: A modularization of a concern that cuts across multiple classes. Transaction management is a good example of a crosscutting concern in enterprise Java applications. In Spring AOP, aspects are implemented by using regular classes (the schema-based approach) or regular classes annotated with the @Aspect annotation (the @AspectJ style).
  • Join point: A point during the execution of a program, such as the execution of a method or the handling of an exception. In Spring AOP, a join point always represents a method execution.
  • Advice: Action taken by an aspect at a particular join point. Different types of advice include “around”, “before” and “after” advice. (Advice types are discussed later.) Many AOP frameworks, including Spring, model an advice as an interceptor and maintain a chain of interceptors around the join point.
  • Pointcut: A predicate that matches join points. Advice is associated with a pointcut expression and runs at any join point matched by the pointcut (for example, the execution of a method with a certain name). The concept of join points as matched by pointcut expressions is central to AOP, and Spring uses the AspectJ pointcut expression language by default.
  • Introduction: Declaring additional methods or fields on behalf of a type. Spring AOP lets you introduce new interfaces (and a corresponding implementation) to any advised object. For example, you could use an introduction to make a bean implement an IsModified interface, to simplify caching. (An introduction is known as an inter-type declaration in the AspectJ community.)
  • Target object: An object being advised by one or more aspects. Also referred to as the “advised object”. Since Spring AOP is implemented by using runtime proxies, this object is always a proxied object.
  • AOP proxy: An object created by the AOP framework in order to implement the aspect contracts (advise method executions and so on). In the Spring Framework, an AOP proxy is a JDK dynamic proxy or a CGLIB proxy.
  • Weaving: linking aspects with other application types or objects to create an advised object. This can be done at compile time (using the AspectJ compiler, for example), load time, or at runtime. Spring AOP, like other pure Java AOP frameworks, performs weaving at runtime.
 
정리를.. 해봐야겠찌...
오늘도 왜 나는 영어를 열심히 안했나 생각하면서....

 

  • Aspect : 측면 - 여러 클래스를 가로지르는 모듈화, 애노테이션이 달린 @Aspect 를 사용하여 구현
  • Join point: 조인포인트 - 메소드 실행 또는 예외 처리와 같은 실행 포인트. Spring AOP에서 조인 포인트는 method represents(실행)
  • Advice: 특정 JoinPoint에서 Aspect가 하는 행동. advice type에는 around, before, after 등이 있다. 이 advice를 interceptor하여 모델링 하고 join point 에 interceptor chain을 유지한다
  • Pointcut: JoinPoint와 일치하는 predicate, Advice는 이 Pointcut 표현식과 연관되며, 이와 일치하는 모든 join point에서 실행된다
  • introduction : type 을 대신하여 추가 메소드 또는 필드를 선언한다. AOP사용 시 advice 된 객체에 새로운 interface(와 corresponding implementation) 을 도입한다. 예를 들어 캐싱을 단순히 하기 위해 bean이 isModified 인터페이스를 구현할 수 있도록 introduction 할 수 있다. (유형 간 선언)
  • Target object : 하나 이상의 Aspect 에게 Advice를 받는 개체이다. "advice object"라고도 한다. Spring AOP는 runtime proxy를 사용하여 구현되므로 항상 프록시된 개체를 말한다
  • Weaving : adviced 된 객체를 생성하기 위해 다른 application types 또는 객체와 Aspect를 연결한다. 이는 compile time, load time, or at runtime 에 수행이 가능하다. Spring AOP는 다른 pure JAVA AOP 프레임워크 처럼 weaving을 수행한다

Spring AOP 는 다음 타입의 Advice 가 포함된다

 

  • Before advice: Advice that runs before a join point but that does not have the ability to prevent execution flow proceeding to the join point (unless it throws an exception). > 이전에 실행되지만 실행 흐름을 막을 능력은 없다(예외발생시키지 않는 한)
  • After returning advice: Advice to be run after a join point completes normally (for example, if a method returns without throwing an exception). > JoinPoint 정상 완료 후 실행할 advice(메서드가 예외를 throw하지않고 return할 때)
  • After throwing advice: Advice to be run if a method exits by throwing an exception. > 메소드가 예외를 던지고 종료될 때 실행할 Advice
  • After (finally) advice: Advice to be run regardless of the means by which a join point exits (normal or exceptional return). > JoinPoint가 종료 방법(정상 또는 예외반환처리 등)에 관계 없이 실행
  • Around advice: Advice that surrounds a join point such as a method invocation. This is the most powerful kind of advice. Around advice can perform custom behavior before and after the method invocation. It is also responsible for choosing whether to proceed to the join point or to shortcut the advised method execution by returning its own return value or throwing an exception. > 가장 강력함. Around advice는 method invocation 전 후에 지정 동작을 수행할 수 있고, JoinPoint로 진행할지, 자체 반환 값을 처리하거나 예외 throw 하여 advice 된 메서드 실행을 shortcut할지의 여부 선택도 가능하다

가장 일반적인 Advice 는 이 Around advice이다

AspectJ와 같은 Spring AOP는 전체 범위의 advice type이 필요하므로 가장 약한 advice 유형을 사용하는 것이 좋다

예시로 메소드 반환 값으로 캐시만 업데이트 해야할 경우 around advice를 쓰기보다는 After returning advice를 쓰는게 낫다. 그러면 오류 가능성이 적은 프로그래밍 모델이 제공 된다.

Around advice에서 사용 되는 JoinPoint에서 process() 메서드를 호출할 필요가 없기 때문에 호출에 실패할 일이 없다

 

모든 Advice parameters 는 객체 배열이 아닌 적절한 type(메소드 실행의 반환 값)의 매개변수로 작업할 수 있도록 statically type으로 지정된다

 

pointcut과 일치하는 joinPoint의 개념은 interceptor만 제공하는 기술과 구별되는 AOP의 핵심 기술이다

pointcuts는 advice가 객체지향계층구조와 독립적인 대상으로 만든다

예를 들어, 선언적 트랜잭션 관리를 제공하는 advice를 여러 개체(service layer 의 모든 bussiness 운영)에 걸친 메소드에 모두 적용할 수 있다

 

 

 

 

5.2. Spring AOP Capabilities and Goals

Spring AOP는 순수한 Java로 구현된다. 특별한 컴파일 과정이 필요없다.

Spring AOP는 클래스 로더 계층 구조를 제어할 필요가 없으므로 서블릿 컨테이너 또는 애플리케이션 서버에서 사용하기에 적합하다. Spring AOP는 현재 메서드 실행 조인 포인트만 지원한다(Spring bean에서 메서드 실행을 조언함).

핵심 Spring AOP API를 중단하지 않고 필드 차단에 대한 지원을 추가할 수 있지만 필드 차단은 구현되지 않는다.

필드 액세스 및 조인 포인트 업데이트를 조언해야 하는 경우 AspectJ와 같은 언어를 사용하기를 권고한다.

AOP에 대한 Spring AOP의 접근 방식은 대부분의 다른 AOP 프레임워크와 다르다다.

목표는 가장 완전한 AOP 구현을 제공하는 것이 아니고(Spring AOP가 상당히 유능하지만), AOP 구현과 Spring IoC 간의 긴밀한 통합을 제공하여 엔터프라이즈 애플리케이션의 일반적인 문제를 해결하는 데 도움을 준다.

예를 들어 Spring Framework의 AOP 기능은 일반적으로 Spring IoC 컨테이너와 함께 사용된다.

Aspect는 일반 빈 정의 구문을 사용하여 구성된다(이는 강력한 "자동 프록시" 기능을 허용하지만). 이것이 다른 AOP 구현과의 중요한 차이이다. 매우 세밀한 개체(일반적으로 도메인 개체)를 어드바이스하는 것과 같은 일부 작업은 Spring AOP로 쉽고 효율적으로 수행할 수 없다. 이럴 때 AspectJ는 최선의 선택이 된다다.

 

그러나 Spring AOP는 AOP에 적합한 엔터프라이즈 Java 애플리케이션의 대부분의 문제에 대해 탁월한 솔루션을 제공하고 있다. Spring AOP는 포괄적인 AOP 솔루션을 제공하기 위해 AspectJ와 경쟁하지는 않는다. Spring AOP와 같은 프록시 기반 프레임워크와 AspectJ와 같은 본격적인 프레임워크 모두 보완적이길 바란다. Spring은 Spring AOP 및 IoC를 AspectJ와 매끄럽게 통합하여 일관된 Spring 기반 애플리케이션 아키텍처 내에서 AOP의 모든 사용을 가능하게 한다.

이 통합은 Spring AOP API 또는 AOP Alliance API에 영향을 미치지 않는다. Spring AOP는 이전 버전과 호환된다.

 

 

* Spring Framework 의 핵심 원칙 중 하나는 non-invasiveness 이다.

Spring 에서는 AspectJ, Spring AOP 둘다 사용이 가능하다

그리고 @AspectJ 애노테이션 또는 Spring XML 구성 접근방식 중에 선택이 가능하다

 

(뭐가 더 낫다 아니다는 개발자가 정하라는 뜻으로 보인다)

 

 

5.3. AOP Proxies

Spring AOP는 기본적으로 AOP proxy용 standard JDK 를 사용한다. 모든 인터페이스(또는 집합)을 프록시할 수 있다. CGLIB 프록시도 사용할 수 있다. 인터페이스가 아닌 프록시 클래스에 필요하다. 기본적으로 비지니스 개체가 interface 를 구현하지 않을 경우 CGLIB가 사용된다. 클래스보다 인터페이스로 사용하는 것이 좋기 때문에 일반적으로 비지니스 인터페이스를 구현한다. CGLIB를 강제 사용할 수 는 있으나 이는 인터페이스에 선언되지 않은 메서드를 advice해야하거나 구체적인 type으로 프록시 개체를 전달해야하는 아주 드문 경우이다.

Spring AOP가 프록시 기반인 것이 중요하다.

https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#aop-understanding-aop-proxies

 

Core Technologies

In the preceding scenario, using @Autowired works well and provides the desired modularity, but determining exactly where the autowired bean definitions are declared is still somewhat ambiguous. For example, as a developer looking at ServiceConfig, how do

docs.spring.io

 
 

5.4. @AspectJ support

@AspectJ는 애노테이션이 붙은 일반 자바클래스로 aspect를 선언하는 스타일을 말한다

AOP 런타임은 순수한 Spring AOP이며 AspectJ 컴파일러나 weaver 에 대한 종속성은 없다

 

Enabling @AspectJ Support with Java Configuration

 

To enable @AspectJ support with Java @Configuration, add the @EnableAspectJAutoProxy annotation

@Configuration
@EnableAspectJAutoProxy
public class AppConfig {

}

 

Enabling @AspectJ Support with XML Configuration

To enable @AspectJ support with XML-based configuration, use the aop:aspectj-autoproxy element
<aop:aspectj-autoproxy/>

 

5.4.2. Declaring an Aspect

@AspectJ 를 활성화하면 @Aspect에 정의된 모든 빈이 자동 감지된다

<bean id="myAspect" class="org.xyz.NotVeryUsefulAspect">
    <!-- configure properties of the aspect here -->
</bean>

 

@Aspect
public class NotVeryUsefulAspect {

}

Advising aspects with other aspects? 

In Spring AOP, aspects themselves cannot be the targets of advice from other aspects. The @Aspect annotation on a class marks it as an aspect and, hence, excludes it from auto-proxying.

 

 

 

5.4.3. Declaring a Pointcut

pointcut은 원하는 joinpoint를 결정하기 때문에 advice 실행 시기를 제어할 수 있다

Spring AOP는 bean에 대한 메소드 실행 joinpoint만 지원하므로 pointcut을 Spring bean의 method 실행과 일치한다고 생각할 수 있다

pointcut 선언은 두 부분으로 구성되어있다. 이름과 매개변수로 구성되는 서명, 원하는 method 실행 결정 pointcut 표현식

@AspectJ 주석 스타일에서 pointcut signature는 정규 메서드 정의에 의해 제공된다

pointcut 표현식은 @Pointcut 애노테이션을 사용하여 표시된다(method serving as the pointcut signature must have a void return type)

@Pointcut("execution(* transfer(..))") // the pointcut expression
private void anyOldTransfer() {} // the pointcut signature

https://www.eclipse.org/aspectj/doc/released/progguide/index.html

 

The AspectJTM Programming Guide

Copyright (c) 1998-2001 Xerox Corporation, 2002-2003 Palo Alto Research Center, Incorporated. All rights reserved.

www.eclipse.org

 

Supported Pointcut Designators

Aspect pointcut 지정자 (PCD)

 

  • execution: For matching method execution join points. This is the primary pointcut designator to use when working with Spring AOP. > 기본 pointcut 지정자
  • within: Limits matching to join points within certain types (the execution of a method declared within a matching type when using Spring AOP). > 특정 타입 내 매칭을 제한함
  • this: Limits matching to join points (the execution of methods when using Spring AOP) where the bean reference (Spring AOP proxy) is an instance of the given type. > Bean참조(AOP proxy)가 주어진 유형의 인스턴트 일치 제한
  • target: Limits matching to join points (the execution of methods when using Spring AOP) where the target object (application object being proxied) is an instance of the given type. > 대상 객체로 일치 제한
  • args: Limits matching to join points (the execution of methods when using Spring AOP) where the arguments are instances of the given types. > 인수가 주어진 유형의 결합 지점 일치 제한
  • @target: Limits matching to join points (the execution of methods when using Spring AOP) where the class of the executing object has an annotation of the given type. > 실행 객체 클래스 일치 제한
  • @args: Limits matching to join points (the execution of methods when using Spring AOP) where the runtime type of the actual arguments passed have annotations of the given types. > 전달 실제 인수의 런타임 유형이 주어진 유형 joinpoint 일치 제한
  • @within: Limits matching to join points within types that have the given annotation (the execution of methods declared in types with the given annotation when using Spring AOP). > 주석에 있는 유형 내 joinpoint 일치 제한
  • @annotation: Limits matching to join points where the subject of the join point (the method being run in Spring AOP) has the given annotation. > joinpoint 주체에 지정된 주석이 있는 주석 포인트 일치 제한

 

 

++  Other pointcut types 

전체 AspectJ 포인트컷 언어는 Spring에서 지원되지 않는 추가 포인트컷 지정자(call, get, set, preinitialization, staticinitialization, initialization, handler, adviceexecution, withincode, cflow, cflowbelow, if, @this 및 @withincode)를 지원한다. Spring AOP에 의해 해석되는 포인트컷 표현식에서 이러한 포인트컷 지정자를 사용하면 IllegalArgumentException이 발생한다.  Spring AOP가 지원하는 포인트컷 지정자 세트는 더 많은 AspectJ 포인트컷 지정자를 지원하기 위해 향후 릴리스에서 확장될 수 있다.

 

 

Spring AOP는 메서드 실행 joinpoint 일치하는 것만 제한하기 때문에 더 좁은 정의를 제공한다

AspectJ 자체는 유형 기반의 semantics을 가지고 실행되는 joinpoint에서 this와 target은 동일한 객체를 참조한다

Spring AOP는 프록시 기반 시스템이며, 프록시 개체 자체와 프록시 뒤의 대상개체를 구분한다

 

 

Due to the proxy-based nature of Spring’s AOP framework, calls within the target object are, by definition, not intercepted. For JDK proxies, only public interface method calls on the proxy can be intercepted. With CGLIB, public and protected method calls on the proxy are intercepted (and even package-visible methods, if necessary). However, common interactions through proxies should always be designed through public signatures.  Note that pointcut definitions are generally matched against any intercepted method. If a pointcut is strictly meant to be public-only, even in a CGLIB proxy scenario with potential non-public interactions through proxies, it needs to be defined accordingly.  If your interception needs include method calls or even constructors within the target class, consider the use of Spring-driven native AspectJ weaving instead of Spring’s proxy-based AOP framework. This constitutes a different mode of AOP usage with different characteristics, so be sure to make yourself familiar with weaving before making a decision.

 

 

PCD bean의 형식

bean(idOrNameOfBean)

 

idOrNameOfBean 토큰은 모든 Spring bean의 이름이 될 수 있다.

* 문자를 사용하는 제한된 와일드카드 지원이 제공되므로 Spring 빈에 대한 일부 명명 규칙을 설정하는 경우 이를 선택하기 위해 빈 PCD 표현식을 작성할 수 있다. 다른 pointcut 지정자의 경우와 마찬가지로 bean PCD는 &&(and), || (또는) 및 ! (부정) 연산자도 동일하다.

 

 

 

Combining Pointcut Expressions

You can combine pointcut expressions by using &&, || and !. You can also refer to pointcut expressions by name. 
@Pointcut("execution(public * *(..))")
private void anyPublicOperation() {} 

@Pointcut("within(com.xyz.myapp.trading..*)")
private void inTrading() {} 

@Pointcut("anyPublicOperation() && inTrading()")
private void tradingOperation() {}
anyPublicOperation > 공용 메서드 실행일 경우 일치
inTrading > 메서드 실행이 있으면 일치
tradingOperation > 공용메서드인데 해당 메서드 실행이 있다면 일치
 
더 복잡한 pointcut 으로 작성하는게 좋음
When referring to pointcuts by name, normal Java visibility rules apply (you can see private pointcuts in the same type, protected pointcuts in the hierarchy, public pointcuts anywhere, and so on). 
 
 

Sharing Common Pointcut Definitions

CommonPointcuts aspect that captures common pointcut expressions for this purpose. 

 

 

@Aspect
public class CommonPointcuts {

    /**
     * A join point is in the web layer if the method is defined
     * in a type in the com.xyz.myapp.web package or any sub-package
     * under that.
     */
    @Pointcut("within(com.xyz.myapp.web..*)")
    public void inWebLayer() {}

    /**
     * A join point is in the service layer if the method is defined
     * in a type in the com.xyz.myapp.service package or any sub-package
     * under that.
     */
    @Pointcut("within(com.xyz.myapp.service..*)")
    public void inServiceLayer() {}

    /**
     * A join point is in the data access layer if the method is defined
     * in a type in the com.xyz.myapp.dao package or any sub-package
     * under that.
     */
    @Pointcut("within(com.xyz.myapp.dao..*)")
    public void inDataAccessLayer() {}

    /**
     * A business service is the execution of any method defined on a service
     * interface. This definition assumes that interfaces are placed in the
     * "service" package, and that implementation types are in sub-packages.
     *
     * If you group service interfaces by functional area (for example,
     * in packages com.xyz.myapp.abc.service and com.xyz.myapp.def.service) then
     * the pointcut expression "execution(* com.xyz.myapp..service.*.*(..))"
     * could be used instead.
     *
     * Alternatively, you can write the expression using the 'bean'
     * PCD, like so "bean(*Service)". (This assumes that you have
     * named your Spring service beans in a consistent fashion.)
     */
    @Pointcut("execution(* com.xyz.myapp..service.*.*(..))")
    public void businessService() {}

    /**
     * A data access operation is the execution of any method defined on a
     * dao interface. This definition assumes that interfaces are placed in the
     * "dao" package, and that implementation types are in sub-packages.
     */
    @Pointcut("execution(* com.xyz.myapp.dao.*.*(..))")
    public void dataAccessOperation() {}

}
 
pointcut 은 필요한 곳 어디에서나 참조할 수 있다
서비스 계층 트랜잭션 작성 시 예
<aop:config>
    <aop:advisor
        pointcut="com.xyz.myapp.CommonPointcuts.businessService()"
        advice-ref="tx-advice"/>
</aop:config>

<tx:advice id="tx-advice">
    <tx:attributes>
        <tx:method name="*" propagation="REQUIRED"/>
    </tx:attributes>
</tx:advice>
 

https://docs.spring.io/spring-framework/docs/current/reference/html/data-access.html#transaction

 

Data Access

The Data Access Object (DAO) support in Spring is aimed at making it easy to work with data access technologies (such as JDBC, Hibernate, or JPA) in a consistent way. This lets you switch between the aforementioned persistence technologies fairly easily, a

docs.spring.io

 
 

 

예제는 그냥 복붙하겠음!!

 

Examples

 

Spring AOP users are likely to use the execution pointcut designator the most often. The format of an execution expression follows:

    execution(modifiers-pattern? ret-type-pattern declaring-type-pattern?name-pattern(param-pattern)
                throws-pattern?)

All parts except the returning type pattern (ret-type-pattern in the preceding snippet), the name pattern, and the parameters pattern are optional. The returning type pattern determines what the return type of the method must be in order for a join point to be matched. * is most frequently used as the returning type pattern. It matches any return type. A fully-qualified type name matches only when the method returns the given type. The name pattern matches the method name. You can use the * wildcard as all or part of a name pattern. If you specify a declaring type pattern, include a trailing . to join it to the name pattern component. The parameters pattern is slightly more complex: () matches a method that takes no parameters, whereas (..) matches any number (zero or more) of parameters. The (*) pattern matches a method that takes one parameter of any type. (*,String) matches a method that takes two parameters. The first can be of any type, while the second must be a String. Consult the Language Semantics section of the AspectJ Programming Guide for more information.

The following examples show some common pointcut expressions:

  • The execution of any public method:
  •     execution(public * *(..))
  • The execution of any method with a name that begins with set:
  •     execution(* set*(..))
  • The execution of any method defined by the AccountService interface:
  •     execution(* com.xyz.service.AccountService.*(..))
  • The execution of any method defined in the service package:
  •     execution(* com.xyz.service.*.*(..))
  • The execution of any method defined in the service package or one of its sub-packages:
  •     execution(* com.xyz.service..*.*(..))
  • Any join point (method execution only in Spring AOP) within the service package:
  •     within(com.xyz.service.*)
  • Any join point (method execution only in Spring AOP) within the service package or one of its sub-packages:
  •     within(com.xyz.service..*)
  • Any join point (method execution only in Spring AOP) where the proxy implements the AccountService interface:
      this is more commonly used in a binding form. See the section on Declaring Advice for how to make the proxy object available in the advice body.
  •     this(com.xyz.service.AccountService)
  • Any join point (method execution only in Spring AOP) where the target object implements the AccountService interface:
      target is more commonly used in a binding form. See the Declaring Advice section for how to make the target object available in the advice body.
  •     target(com.xyz.service.AccountService)
  • Any join point (method execution only in Spring AOP) that takes a single parameter and where the argument passed at runtime is Serializable:
      args is more commonly used in a binding form. See the Declaring Advice section for how to make the method arguments available in the advice body.

    Note that the pointcut given in this example is different from execution(* *(java.io.Serializable)). The args version matches if the argument passed at runtime is Serializable, and the execution version matches if the method signature declares a single parameter of type Serializable.

  •     args(java.io.Serializable)
  • Any join point (method execution only in Spring AOP) where the target object has a @Transactional annotation:
      You can also use @target in a binding form. See the Declaring Advice section for how to make the annotation object available in the advice body.
  •     @target(org.springframework.transaction.annotation.Transactional)
  • Any join point (method execution only in Spring AOP) where the declared type of the target object has an @Transactional annotation:
      You can also use @within in a binding form. See the Declaring Advice section for how to make the annotation object available in the advice body.
  •     @within(org.springframework.transaction.annotation.Transactional)
  • Any join point (method execution only in Spring AOP) where the executing method has an @Transactional annotation:
      You can also use @annotation in a binding form. See the Declaring Advice section for how to make the annotation object available in the advice body.
  •     @annotation(org.springframework.transaction.annotation.Transactional)
  • Any join point (method execution only in Spring AOP) which takes a single parameter, and where the runtime type of the argument passed has the @Classified annotation:
      You can also use @args in a binding form. See the Declaring Advice section how to make the annotation object(s) available in the advice body.
  •     @args(com.xyz.security.Classified)
  • Any join point (method execution only in Spring AOP) on a Spring bean named tradeService:
  •     bean(tradeService)
  • Any join point (method execution only in Spring AOP) on Spring beans having names that match the wildcard expression *Service:
  •     bean(*Service)
 

 

 

Writing Good Pointcuts

컴파일하는 동안 AspectJ는 매칭 성능을 최적화하기 위해 포인트컷을 처리한다.

코드를 검사하고 각 조인 포인트가 주어진 포인트컷과 일치하는지(정적 또는 동적으로) 결정하는 것은 비용이 많이 드는 프로세스이다.

(동적 일치는 일치가 정적 분석에서 완전히 결정될 수 없으며 코드가 실행 중일 때 실제 일치가 있는지 확인하기 위해 코드에 테스트가 배치됨을 의미)

포인트컷 선언을 처음 만났을 때 AspectJ는 이를 매칭 프로세스를 위한 최적의 형태로 재작성하게 된다. 이것은 기본적으로 pointcut은 DNF(Disjunctive Normal Form)로 재작성되고 ​​pointcut의 구성 요소는 평가 비용이 저렴한 구성 요소가 먼저 확인되도록 정렬된다는 의미이다. 이는 다양한 포인트컷 지정자의 성능을 이해하는 것에 대해 걱정할 필요가 없으며 포인트컷 선언에서 순서에 상관없이 제공할 수 있음을 의미한다.  

그러나 AspectJ는 오직 그것을 들리는 대로만 작업한다.

최적의 일치 성능을 위해서는 달성하려는 것이 무엇인지 생각하고 정의에서 일치 항목에 대한 검색 공간을 최대한 좁혀야 한다. 기존 지정자는 자연스럽게 종류, 범위 및 문맥의 세 그룹 중 하나에 속한다.

 

Kinded 지정자는 실행, 가져오기, 설정, 호출 및 핸들러와 같은 특정 종류의 조인 포인트를 선택한다.

범위 지정자는 관심 있는 조인 포인트 그룹(아마도 많은 종류)을 선택한다: 코드 내 및 코드 내  컨텍스트 지정자 일치(및 선택적으로 바인딩)는 컨텍스트(this, target 및 @annotation)를 기반.  

 

잘 작성된 pointcut은 적어도 처음 두 가지 유형(kindd 및 scoping)을 포함해야한다.

 

조인 포인트 컨텍스트를 기반으로 일치시킬 컨텍스트 지정자를 포함하거나 어드바이스에서 사용하기 위해 해당 컨텍스트를 바인딩할 수 있다.

 

종류 지정자만 제공하거나 상황별 지정자만 제공하면 작동하지만 추가 처리 및 분석으로 인해 위빙 성능(사용된 시간 및 메모리)에 영향을 미칠 수 있다.

스코핑 지정자는 매칭이 매우 빠르며 이를 사용하면 AspectJ가 더 이상 처리되지 않아야 하는 조인 포인트 그룹을 매우 빠르게 해제할 수 있다.

 

좋은 pointcut은 가능하면 항상 하나를 포함해야 합니다.

 

728x90