Spring AspectJ AOP 전체 예제 (Maven)

우선 Maven 프로젝트 를 새로 만 들 고 프로젝트 의 pom. xml 에 spring aop 관련 의존 항목 을 추가 합 니 다.
다음은 완전한 pom. xml 입 니 다.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>cn.outofmemory</groupId>
	<artifactId>spring-aop-aspect</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>spring-aop-aspect</name>
	<url>http://maven.apache.org</url>
	<properties>
		<spring.version>3.1.1.RELEASE</spring.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>1.6.12</version>
		</dependency>
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.6.12</version>
		</dependency>
		<dependency>
			<groupId>cglib</groupId>
			<artifactId>cglib</artifactId>
			<version>2.2</version>
		</dependency>
	</dependencies></project>

maven 에서 우 리 는 spring op 과 관련 된 의존 도 를 도입 했다. aspectj 와 관련 된 가방 은 두 가지 가 있 는데 cglib 는 필수 적 이다.
다음은 프로젝트 에 Service 클래스 PersonService 를 새로 만 듭 니 다. 이것 은 업무 코드 이 고 AOP 가 주입 한 목표 클래스 입 니 다.
package cn.outofmemory.spring_aop_aspect;

import org.springframework.stereotype.Service;

@Service
public class PersonService {

	public void addPerson(String personName) {
		System.out.println("add person " + personName);
	}
	
	public boolean deletePerson(String personName) {
		System.out.println("delete person " + personName) ;
		return true;
	}
	
	public void editPerson(String personName) {
		System.out.println("edit person " + personName);
		throw new RuntimeException("edit person throw exception");
	}
	
}

PersonService 클래스 에서 세 가지 방법 을 정 의 했 습 니 다. addPerson 방법 은 반환 값 이 없 으 며, deletePerson 방법 은 반환 값 이 있 으 며, editPerson 방법 은 실행 시의 이상 을 던 집 니 다.
다음은 Aspect 류 를 보 겠 습 니 다.
package cn.outofmemory.spring_aop_aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class SimpleAspect {
	@Pointcut("execution(* cn.outofmemory.spring_aop_aspect.*Service*.*(..))")
	public void pointCut() {
	}

	@After("pointCut()")
	public void after(JoinPoint joinPoint) {
		System.out.println("after aspect executed");
	}

	@Before("pointCut()")
	public void before(JoinPoint joinPoint) {
		//                
		//Object[] args = joinPoint.getArgs();
		System.out.println("before aspect executing");
	}

	@AfterReturning(pointcut = "pointCut()", returning = "returnVal")
	public void afterReturning(JoinPoint joinPoint, Object returnVal) {
		System.out.println("afterReturning executed, return result is "
				+ returnVal);
	}

	@Around("pointCut()")
	public void around(ProceedingJoinPoint pjp) throws Throwable {
		System.out.println("around start..");
		try {
			pjp.proceed();
		} catch (Throwable ex) {
			System.out.println("error in around");
			throw ex;
		}
		System.out.println("around end");
	}

	@AfterThrowing(pointcut = "pointCut()", throwing = "error")
	public void afterThrowing(JoinPoint jp, Throwable error) {
		System.out.println("error:" + error);
	}
}

Simple Aspect 클래스 의 첫 번 째 방법 은 pointCut () 방법 입 니 다. 이 방법 은 실행 내용 이 없고 @ Pointcut 의 주석 만 있 습 니 다. 다른 방법 은 이 주석 에서 지정 한 pointcut 표현 식 을 참조 합 니 다.
다른 몇 가지 방법 은 각종 Advice 유형의 방법 으로 이 루어 지 는데 이런 방법 에서 JoinPoint 인 스 턴 스 를 통 해 방법 이 실 행 된 문맥 정보, 매개 변수 정 보 를 얻 을 수 있 습 니 다.After Returning 과 After Throwing, After 세 가지 다른 Advice 의 실행 순 서 를 주의해 야 합 니 다.
spring 프레임 워 크 와 aspectj, cglib 의 지원 이 있 습 니 다. 우 리 는 위의 두 가지 유형 만 실현 하면 spring op 의 기능 을 사용 할 수 있 습 니 다. 다음은 spring 의 프로필 에 spring op 을 어떻게 설정 하 는 지 보 겠 습 니 다.
<?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"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                           http://www.springframework.org/schema/aop
                           http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context-3.1.xsd">
    <aop:aspectj-autoproxy />
    <context:component-scan base-package="cn.outofmemory" /> 
</beans>

beans 노드 에 op 네 임 스페이스 를 지정 해 야 합 니 다. chema Location 주 소 를 지정 하고 op 을 사용 하려 면 추가 <aop:aspectj-autoproxy/> 만 하면 됩 니 다. 노드 는 bean 을 자동 으로 검색 하 는 네 임 스페이스 를 지정 합 니 다.
마지막 으로 op 의 효 과 를 테스트 하려 면 프로그램의 입구 클래스 로 App 클래스 를 새로 만들어 야 합 니 다.
package cn.outofmemory.spring_aop_aspect;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


/**
 * Hello world!
 *
 */
public class App 
{
    public static void main( String[] args )
    {
    	ApplicationContext appContext = new ClassPathXmlApplicationContext("/appContext.xml");
    	PersonService personService = appContext.getBean(PersonService.class);
    	String personName = "Jim";
    	personService.addPerson(personName);
    	personService.deletePerson(personName);
    	personService.editPerson(personName);
    	((ClassPathXmlApplicationContext)appContext).close();
    }
}

이 클래스 에서 저 희 는 applicationContext 를 초기 화 한 다음 에 PersonService 의 인 스 턴 스 를 얻 고 addPerson, deletePerson, editPerson 방법 을 실행 하 며 마지막 으로 applicationContext 를 닫 습 니 다.
그 실행 결 과 는 다음 과 같다.
before aspect executing
around start..
add person Jim
after aspect executed
around end
afterReturning executed, return result is null
-------------------------------------
before aspect executing
around start..
delete person Jim
after aspect executed
around end
afterReturning executed, return result is null
----------------------------------------
before aspect executing
around start..
edit person Jim
after aspect executed
error in around
error:java.lang.RuntimeException: edit person throw exception
Exception in thread ...
위 에서 실행 한 결 과 를 보면 우리 가 실행 해 야 할 Before, around, after, after Returning, after Throwing 이 모두 정상적으로 실행 되 었 음 을 알 수 있다.

좋은 웹페이지 즐겨찾기