[JAVA] Spring aop 範例

摘要:Spring aop 範例

在專案中常常遇到希望在進某個method時,

需要在其之前進行驗證或記錄資訊.

Spring aop 可以完成此目的

先在maven中加入必要的dependency

<!-- Spring AOP + AspectJ -->
		<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.11</version>
		</dependency>

		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.6.11</version>
		</dependency>

在spring 設定檔中加入<aop:aspectj-autoproxy /> 並註冊Aspect介入的bean

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-4.0.xsd 
	http://www.springframework.org/schema/mvc 
	http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd 
	http://www.springframework.org/schema/context 
	http://www.springframework.org/schema/context/spring-context-4.0.xsd
	http://www.springframework.org/schema/aop 
	http://www.springframework.org/schema/aop/spring-aop-4.0.xsd 
	">
	
    <aop:aspectj-autoproxy />
	           
	<!-- Aspect related bean instantiation -->
	<bean id="validationAspect" class="proj.aop.ServiceAspect" />
</beans>
</xml>

接下來撰寫介入的bean,@Aspect 標注為介入的bean 並利用 @Pointcut("execution(* proj.service.impl.*.*(..))") 標注需要介入的範圍 
然後設定介入後執行哪個method標注@Around("serviceLayerPointcut()")

package proj.aop;

import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class ServiceAspect {

	private static final Logger logger = Logger.getLogger(ServiceAspect.class);

	@Pointcut("execution(* proj.service.impl.*.*(..))")
	public void serviceLayerPointcut() {

	}

	@Around("serviceLayerPointcut()")
	public Object serviceBefore(ProceedingJoinPoint pjp) throws Throwable {
		logger.debug("serviceBefore!!!");
		Object[] args = pjp.getArgs();
		return pjp.proceed(args);
	}

}

​Pointcut 範圍表示範例
​  @Pointcut("(((execution(* com.*.service.impl.*.*(..)) ) || execution(* com.*.*.service.impl.*.*(..))) "
	  		+ "&& ( !(execution(* com.framework..*.*(..))) "
	  		+ "&&  !(execution(* com.security..*.*(..))) "
	  		+ "&& !(@annotation(com.framework.validation.DisableValidation))))")

以上