spring整合aspectj实现aop的;一个简单案例(annotation)

  • Post author:
  • Post category:其他



1.*************代理类*******************

package cn.xxxx.aopAnnotation;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
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;

/**
 * @author: xxxxx
 * @creationTime:2017年xx月xx日 上午10:21:58
 * @version: 1.1
 */
@Component
@Aspect
public class CustomerServiceHelper {
	@Pointcut("execution(* cn.xxxx.aopAnnotation..*(..))")
	private void myPointCut() {
	};

	@Pointcut("execution(* cn.xxxx.aopAnnotation..update(..))")
	private void myPointCut1() {
	};

	@Pointcut("execution(* cn.xxxx.aopAnnotation..search(..))")
	private void myPointCut2() {
	};

	@Before("myPointCut()")
	public void before() {
		System.out.println("前置通知");
	}

	@Around("myPointCut1()||myPointCut2()")
	public Object around(ProceedingJoinPoint pjp) throws Throwable {
		System.out.println("环绕前");
		Object value = pjp.proceed();
		System.out.println("环绕后");
		return value;
	}

	@AfterThrowing(value = "execution(* cn.xxxx.aopAnnotation..*(..))", throwing = "ex")
	public void afterThrowing(JoinPoint jp, Throwable ex) {
		System.out.println("异常抛出通知" + ex);
	}

	@After("execution(* cn.xxxx.aopAnnotation..*(..))")
	public void after() {
		System.out.println("最终通知");
	}
}


2.****************配置文件的书写***************

<?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:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
						http://www.springframework.org/schema/beans/spring-beans.xsd
						http://www.springframework.org/schema/context
						http://www.springframework.org/schema/context/spring-context.xsd
						http://www.springframework.org/schema/aop
						http://www.springframework.org/schema/aop/spring-aop.xsd
						http://www.springframework.org/schema/tx 
						http://www.springframework.org/schema/tx/spring-tx.xsd">
						
	<!--用于指定spring扫描注解的包-->
	<context:component-scan base-package="cn.xxxx.aopAnnotation"/>		
	<!--开启aspectj注解自动代理,如果不开启,spring容器并不知道@Aspect,@Before..是什么东西-->
	<aop:aspectj-autoproxy proxy-target-class="true"/>
</beans>



版权声明:本文为Simon_hxc原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。