AOP를 구현하는 3가지 방법
1) POJO Class를 이용한 AOP구현 (전통적인 방식)
2) 스프링 API를 이용한 AOP구현 (<aop> 엘리먼트 이용)
3) 어노테이션을 이용한 AOP 구현 (@Aspect으로 직접 구현)
1. 기능 구현을 위한 인터페이스
package spring.aop.ch04;
public interface Human {
public void sayName();
}
2. 기능 구현 클래스
package spring.aop.ch04;
public class HumanImpl implements Human {
@Override
public void sayName() {
// int sum = 10/0; // @AfterThrowing 테스트를 위한 의도적인 부분 내용
System.out.println("sayName() => 내 이름은 홍길동입니다.");
}
}
3. 공통 기능을 담당하는 클래스 (AOP)
package spring.aop.ch04;
import org.aspectj.lang.annotation.Pointcut;
@Aspect // 공통 관심 모듈의 기능(메서드)을 advice로 연결해주는 어노테이션
public class MannerAOP {
@Pointcut("execution(public * Human.sayName())") // 직접 명시자로 포인트컷을 써주기
public void sayNamePointcut() {
System.out.println("sayNamePointcut() 메서드 호출");
@Before("sayNamePointcut()") // 위의 sayNamePointcut 메서드 이전에 이하 메서드를 먼저 실행
public void hi() {
System.out.println("@Before: 이름 호출하기 전");
}
@AfterReturning("sayNamePointcut()")
public void after() {
System.out.println("@After: 이름 호출 끝난 후");
}
@AfterThrowing("sayNamePointcut()")
public void ex() {
System.out.println("@AfterThrowing: 예외 발생");
}
}
4. 설정 파일
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd">
<!-- @Aspectj 어노테이션 기반의 aspect를 자동으로 등록해주는 엘리먼트 -->
<aop:aspectj-autoproxy />
<bean id="human" class="spring.aop.ch04.HumanImpl" />
<bean id="manner" class="spring.aop.ch04.MannerAOP" />
</beans>
5. 실행 클래스
package spring.aop.ch04;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainAOP {
public static void main(String[] args) {
AbstractApplicationContext context =
new ClassPathXmlApplicationContext("applicationContext4.xml");
context.registerShutdownHook();
Human msgBean =
context.getBean("human", Human.class);
msgBean.sayName();
context.close();
}
}
@Before: 이름 호출하기 전
sayName() => 내 이름은 홍길동입니다.
@After: 이름 호출 끝난 후
' Spring Framework' 카테고리의 다른 글
Spring에서 데이터베이스 연동하기: KBO 구단 조회 (0) | 2016.04.04 |
---|---|
Spring 과 DB (0) | 2016.04.04 |
AOP라는 엘리먼트를 이용해 AOP 설정을 하는 방법 (0) | 2016.04.01 |
AOP 용어 및 개념 이해를 위한 예제 (0) | 2016.04.01 |
AOP 실습 (0) | 2016.03.31 |