spring2.5开启注解AOP

第一步:开启注解

<?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-2.5.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-2.5.xsd
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<!-- 开启注解 -->
	<context:annotation-config />
	 <!-- 配置注解扫面路径 -->
	 <context:component-scan base-package="com.ssh"/>
	<!-- 启动对@AspectJ注解的支持 -->     
	<aop:aspectj-autoproxy/>
</beans>

第二步:


package com.ssh.aop;

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;

@Aspect
public class AspectAop {

	/**
	 * 前置通知
	 */
	@Before("execution(* com.ssh.service.UserService.getUser(..))")
	public void before() {
		System.out.println("前置通知....");
	}

	/**
	 * 后置通知 returnVal,切点方法执行后的返回值
	 */
	@AfterReturning(value = "execution(* com.ssh.service.UserService.getUser(..))", returning = "returnVal")
	public void AfterReturning(Object returnVal) {
		System.out.println("后置通知...." + returnVal);
	}

	/**
	 * 环绕通知
	 * 
	 * @param joinPoint 可用于执行切点的类
	 * @return
	 * @throws Throwable
	 */
	@Around("execution(* com.ssh.service.UserService.getUser(..))")
	public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
		System.out.println("环绕通知前....");
		Object obj = (Object) joinPoint.proceed();
		System.out.println("环绕通知后....");
		return obj;
	}

	/**
	 * 抛出通知
	 * 
	 * @param e
	 */
	@AfterThrowing(value = "execution(* com.ssh.service.UserService.getUser(..))", throwing = "e")
	public void afterThrowable(Throwable e) {
		System.out.println("出现异常:msg=" + e.getMessage());
	}

	/**
	 * 无论什么情况下都会执行的方法
	 */
	@After(value = "execution(* com.ssh.service.UserService.getUser(..))")
	public void after() {
		System.out.println("最终通知....");
	}
}

可在切入点方法里面加入:

System.out.println("getuser方法体***********************************************>>");

以便测试运行顺序

当程序运行到getUser(...)方法时控制台输出:

猜你喜欢

转载自blog.csdn.net/qq3892997/article/details/81781395
今日推荐