728x90
AOP
보안이나 로그, 트랜잭션과 같이 비즈니스 로직은 아니지만, 반드시 처리가 필요한 부분을 스프링에서는횡단 관심사
라고 한다. AOP는 이러한 횡단 관심사를 모듈로 분리하는 프로그래밍의 패러다임이다. 즉, 문제를 해결하기 위한 핵심 관심사항
과 전체에 적용되는 공통 관심사항
을 분리하여 프로그래밍함으로써 공통 모듈을 여러 코드에 쉽게 적용할 수 있도록 도와준다.
부가기능
: 공통기능으로 어플리케이션 전반에 걸쳐 필요한 기능 ➜ 로깅, 트랜잭션, 보안, 예외처리 등핵심기능
: 핵심 비즈니스 로직 ➜ 로그인, 회원가입, 계좌이체 등
AOP 주요 용어
Advice
: 실질적인 부가 기능 로직을 정의하는 곳Join point
:advice
가 적용될 수 있는 모든 시점. Spring AOP에서는 메서드 호출 시점만 지원Pointcut
:Join point
중advice
가 적용될 위치를 선별.Target
:advice
의 대상이 되는 객체로, 핵심 로직을 구현하는 클래스이다.Aspect
: 여러 객체에 공통으로 적용되는 부가 기능을 의미 (예. 보안, 로깅, 트랜잭션 등)Weaving
:Advice
를 핵심 로직 코드에 삽입하는 것Advisor
:advice
+pointcut

부가기능의 실행 시점
- 핵심기능의 메서드호출 전:
Before advice
,@Before
- 핵심기능의 메서드호출 후:
After advice
,@After
- 핵심기능의 메서드 정상 처리시:
afterReturning advice
,@AfterReturning
- 핵심기능의 메서드 예외 발생시:
afterThrowing advice
,@AfterThrowing
- 모두 포함한 경우 :
around advice
@Around
부가기능(공통 관심사항)의 대표적인 예
- loggin and Tracking ➜ around
- Transaction Management ➜ around
- Security ➜ before
- Caching ➜ around
- Error Handling ➜ after throwing
- Performance Monitoring ➜ around
실습 순서
① AOP 의존성 등록
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
② 타겟 객체 생성
핵심 기능을 구현한 빈 생성
// target 객체 : 핵심기능 구현
public class UserService {
public String sayEcho() {
System.out.println("sayEcho");
return "hello";
}
public String callEcho() {
System.out.println("callEcho");
return "world";
}
}
③ aspect 객체 생성
부가 기능을 구현한 빈 생성
@Aspect
어노테이션 지정pointcut
지정 : 어떤 핵심기능의 메서드인지 알려주는 기능
💡 Pointcut 표현식
@Pointcut("execution(수식어 리턴타입 클래스이름(파라미터))")
- 각 패턴은 *를 이용해 모든 값을 표현 가능
- 클래스이름에서 패키지 이름 뒤에 ..을 쓰면 서브패키지도 찾는다
- 예) execution(* com.app.aop..*.select*(..))
➜ com.app.aop 패키지 및 하위패키지에 있는 파라미터가 0개 이상인 이름이 select로 시작하는 메서드 호출(리턴타입 무관)
// aspect 객체 : target인 UserService의 메서드호출 시 위빙
@Aspect
public class BeforeAspect {
// pointcut
@Pointcut("execution(public String sayEcho())")
public void xxx() {
}
// advice
@Before("xxx()") // sayEcho가 호출되기 전 실행
public void method2() {
// 부가기능 구현
System.out.println("BeforeAspect.method2");
}
/**************************************/
// advice + pointcut 같이 표현
@Before("execution( * callEcho(..))") // callEcho가 호출되기 전 실행
public void method3() {
System.out.println("BeforeAspect.method3");
}
}
④ target과 aspect 빈 모두 xml에 등록
<bean id="aspect" class="com.aspect.BeforeAspect"/>
<bean id="target" class="com.service.UserService"/>
⑤ @Aspect 어노테이션 활성화
Namespaces
에서 aop
체크
<aop:aspectj-autoproxy/>
⑥ Main 작성
ApplicationContext ctx =
new GenericXmlApplicationContext("classpath:com/config/user.xml");
UserService service = ctx.getBean("target", UserService.class);
System.out.println(service.sayEcho());
System.out.println(service.callEcho());
실행결과

728x90
'WebServer > Spring' 카테고리의 다른 글
[Spring] Spring에서의 MyBatis 연동 (0) | 2023.09.15 |
---|---|
[Spring] 빈 객체 스캔 (component-scan) (0) | 2023.09.14 |
[Spring] SpEL (Spring Expression Language) (0) | 2023.09.14 |
[Spring] I18N 다국어 처리하기 (MessageSource) (0) | 2023.09.13 |
[Spring] BeanFactoryPostProcessor를 이용한 설정 메타데이터 정의 (0) | 2023.09.13 |
728x90
AOP
보안이나 로그, 트랜잭션과 같이 비즈니스 로직은 아니지만, 반드시 처리가 필요한 부분을 스프링에서는횡단 관심사
라고 한다. AOP는 이러한 횡단 관심사를 모듈로 분리하는 프로그래밍의 패러다임이다. 즉, 문제를 해결하기 위한 핵심 관심사항
과 전체에 적용되는 공통 관심사항
을 분리하여 프로그래밍함으로써 공통 모듈을 여러 코드에 쉽게 적용할 수 있도록 도와준다.
부가기능
: 공통기능으로 어플리케이션 전반에 걸쳐 필요한 기능 ➜ 로깅, 트랜잭션, 보안, 예외처리 등핵심기능
: 핵심 비즈니스 로직 ➜ 로그인, 회원가입, 계좌이체 등
AOP 주요 용어
Advice
: 실질적인 부가 기능 로직을 정의하는 곳Join point
:advice
가 적용될 수 있는 모든 시점. Spring AOP에서는 메서드 호출 시점만 지원Pointcut
:Join point
중advice
가 적용될 위치를 선별.Target
:advice
의 대상이 되는 객체로, 핵심 로직을 구현하는 클래스이다.Aspect
: 여러 객체에 공통으로 적용되는 부가 기능을 의미 (예. 보안, 로깅, 트랜잭션 등)Weaving
:Advice
를 핵심 로직 코드에 삽입하는 것Advisor
:advice
+pointcut

부가기능의 실행 시점
- 핵심기능의 메서드호출 전:
Before advice
,@Before
- 핵심기능의 메서드호출 후:
After advice
,@After
- 핵심기능의 메서드 정상 처리시:
afterReturning advice
,@AfterReturning
- 핵심기능의 메서드 예외 발생시:
afterThrowing advice
,@AfterThrowing
- 모두 포함한 경우 :
around advice
@Around
부가기능(공통 관심사항)의 대표적인 예
- loggin and Tracking ➜ around
- Transaction Management ➜ around
- Security ➜ before
- Caching ➜ around
- Error Handling ➜ after throwing
- Performance Monitoring ➜ around
실습 순서
① AOP 의존성 등록
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
② 타겟 객체 생성
핵심 기능을 구현한 빈 생성
// target 객체 : 핵심기능 구현
public class UserService {
public String sayEcho() {
System.out.println("sayEcho");
return "hello";
}
public String callEcho() {
System.out.println("callEcho");
return "world";
}
}
③ aspect 객체 생성
부가 기능을 구현한 빈 생성
@Aspect
어노테이션 지정pointcut
지정 : 어떤 핵심기능의 메서드인지 알려주는 기능
💡 Pointcut 표현식
@Pointcut("execution(수식어 리턴타입 클래스이름(파라미터))")
- 각 패턴은 *를 이용해 모든 값을 표현 가능
- 클래스이름에서 패키지 이름 뒤에 ..을 쓰면 서브패키지도 찾는다
- 예) execution(* com.app.aop..*.select*(..))
➜ com.app.aop 패키지 및 하위패키지에 있는 파라미터가 0개 이상인 이름이 select로 시작하는 메서드 호출(리턴타입 무관)
// aspect 객체 : target인 UserService의 메서드호출 시 위빙
@Aspect
public class BeforeAspect {
// pointcut
@Pointcut("execution(public String sayEcho())")
public void xxx() {
}
// advice
@Before("xxx()") // sayEcho가 호출되기 전 실행
public void method2() {
// 부가기능 구현
System.out.println("BeforeAspect.method2");
}
/**************************************/
// advice + pointcut 같이 표현
@Before("execution( * callEcho(..))") // callEcho가 호출되기 전 실행
public void method3() {
System.out.println("BeforeAspect.method3");
}
}
④ target과 aspect 빈 모두 xml에 등록
<bean id="aspect" class="com.aspect.BeforeAspect"/>
<bean id="target" class="com.service.UserService"/>
⑤ @Aspect 어노테이션 활성화
Namespaces
에서 aop
체크
<aop:aspectj-autoproxy/>
⑥ Main 작성
ApplicationContext ctx =
new GenericXmlApplicationContext("classpath:com/config/user.xml");
UserService service = ctx.getBean("target", UserService.class);
System.out.println(service.sayEcho());
System.out.println(service.callEcho());
실행결과

728x90
'WebServer > Spring' 카테고리의 다른 글
[Spring] Spring에서의 MyBatis 연동 (0) | 2023.09.15 |
---|---|
[Spring] 빈 객체 스캔 (component-scan) (0) | 2023.09.14 |
[Spring] SpEL (Spring Expression Language) (0) | 2023.09.14 |
[Spring] I18N 다국어 처리하기 (MessageSource) (0) | 2023.09.13 |
[Spring] BeanFactoryPostProcessor를 이용한 설정 메타데이터 정의 (0) | 2023.09.13 |