Spring AOP(注解前置+后置通知)

基于注解Spring AOP编程

Spring中使用@AspectJ切面,必须启用Spring对@AspectJ切面配置的支持。

xml 复制代码
<aop:aspectj-autoproxy/>



代码片段

java 复制代码
package com.hk.eshop.anno;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;


@Aspect
public class AuditAspect {

    //定义空方法
    //相当于基于XML AOP中:
    //<aop:pointcut id="save" expression="execution(* com.hk.eshop.anno.UserMng.save(..))" />
    @Pointcut(value="execution(* com.hk.eshop.anno.UserMng.save(..))")
    public void save(){};

    //定义空方法
    //相当于基于XML AOP中:
    //<aop:pointcut id="find" expression="execution(* com.hk.eshop.anno.UserMng.find(..))" />
    @Pointcut(value="execution(* com.hk.eshop.anno.UserMng.find(..))")
    public void find(){};


    //相当于基于XML AOP中:<aop:before pointcut-ref="save" method="audit"/>
    //					  <aop:before pointcut-ref="find" method="audit"/>
    @Before(value="save() || find()")
    public void audit(JoinPoint joinPoint)
    {
        Object [] args = joinPoint.getArgs();
        Signature sgn = joinPoint.getSignature();
        System.out.println("审计开始================================"+sgn.getName());
        for(int i=0;i<args.length;i++)
        {
            System.out.println("第"+(i+1)+"个参数="+args[i]);
        }
        System.out.println("================================审计结束");
        System.out.println("切入点表达式="+joinPoint.toString());
    }
}


package com.hk.eshop.anno;

public class UserMng {
    public String save(String id, String name) {
        System.out.println("save() id="+id+",name="+name);
        return "save() id="+id+",name="+name;
    }

    public String find(String id) {
        System.out.println("find() id="+id);
        return "find() id="+id;
    }
}


<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:p="http://www.springframework.org/schema/p"
       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/context
	http://www.springframework.org/schema/context/spring-context-3.0.xsd
	http://www.springframework.org/schema/aop
	http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

    <context:component-scan base-package="com.hk.eshop"/>

    <bean id="userMng" class="com.hk.eshop.anno.UserMng"/>
    <bean id="auditAspect" class="com.hk.eshop.anno.AuditAspect"/>

    <aop:aspectj-autoproxy/>
</beans>


package com.hk.eshop.anno;

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

public class Main {
    public static void main( String[] args ) throws Exception
    {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
        System.out.println("#####################最终通知#######################");
        UserMng umng = (UserMng)ctx.getBean("userMng");
        umng.save("1","Java");
        umng.find("2");
        System.out.println("#####################环绕通知#######################");

    }
}



代码片段

java 复制代码
package com.hk.eshop.anno;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;


@Aspect
public class LogAspect {

	//定义空方法
	//相当于基于XML AOP中:
	//<aop:pointcut id="save" expression="execution(* com.hk.eshop.anno.OrgMng.saveOrg(..))" />
	@Pointcut(value="execution(* com.hk.eshop.anno.OrgMng.saveOrg(..))")
	public void saveOrg(){};

	//定义空方法
	//相当于基于XML AOP中:
	//<aop:pointcut id="find" expression="execution(* com.hk.eshop.anno.OrgMng.findOrg(..))" />
	@Pointcut(value="execution(* com.hk.eshop.anno.OrgMng.findOrg(..))")
	public void findOrg(){};

	//相当于基于XML AOP中:<aop:AfterReturning pointcut-ref="saveOrg" method="audit" returning="returnValue"/>
	//					  <aop:AfterReturning pointcut-ref="findOrg" method="audit" returning="returnValue"/>
	@AfterReturning(value="saveOrg() || findOrg()",returning="returnValue")
	public void audit(JoinPoint joinPoint,Object returnValue)
	{
		Object [] args = joinPoint.getArgs();
		Signature sgn = joinPoint.getSignature();
		System.out.println("日志记录开始================================"+sgn.getName());
		for(int i=0;i<args.length;i++)
		{
			System.out.println("第"+(i+1)+"个参数="+args[i]);
		}
		System.out.println("================================日志记录结束");
		System.out.println("切入点表达式="+joinPoint.toString());
		System.out.println("目标对象方法的返回值:"+returnValue);
	}
}



package com.hk.eshop.anno;

public class OrgMng {
    public String save(String id, String name){
        System.out.println("save() id="+id+",name="+name);
        return "save() id="+id+",name="+name;
    }

    public String find(String id){
        System.out.println("find() id="+id);
        return "find() id="+id;
    }
}


package com.hk.eshop.anno;

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

public class Main {
    public static void main( String[] args ) throws Exception
    {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
        System.out.println("#####################最终通知#######################");
        UserMng umng = (UserMng)ctx.getBean("userMng");
        //umng.save("1","Java");
        //umng.find("2");
        System.out.println("#####################环绕通知#######################");

        OrgMng omng = (OrgMng) ctx.getBean("orgMng");
        omng.save("root", "Java");
        omng.find("root");


    }
}


<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:p="http://www.springframework.org/schema/p"
       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/context
	http://www.springframework.org/schema/context/spring-context-3.0.xsd
	http://www.springframework.org/schema/aop
	http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

    <context:component-scan base-package="com.hk.eshop"/>

    <bean id="userMng" class="com.hk.eshop.anno.UserMng"/>
    <bean id="auditAspect" class="com.hk.eshop.anno.AuditAspect"/>

    <bean id="orgMng" class="com.hk.eshop.anno.OrgMng"/>
    <bean id="logAspect" class="com.hk.eshop.anno.LogAspect"/>

    <aop:aspectj-autoproxy/>
</beans>






代码片段

java 复制代码
package com.hk.eshop.anno;

public class RoleExistException extends Exception{
    public RoleExistException(String msg)
    {
        super(msg);
    }
}


package com.hk.eshop.anno;

public class RoleNoFoundException extends Exception{
    public RoleNoFoundException(String msg)
    {
        super(msg);
    }
}


package com.hk.eshop.anno;


public class RoleMng {
    public String saveRole(String id,String role) throws RoleExistException
    {
        if("admin".equals(id))
            throw new RoleExistException("管理员角色已经存在");
        System.out.println("调用RoleMng.saveRole()方法 id="+id+",role="+role);
        return "saveRole id="+id+",role="+role;
    }

    public String findRole(String id) throws RoleNoFoundException
    {
        if("admin".equals(id))
            throw new RoleNoFoundException("管理员角色未发现");
        System.out.println("调用RoleMng.findRole()方法 id="+id);
        return "findRole id="+id;
    }
}


package com.hk.eshop.anno;


import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class UsedTimeAspect {

    //定义空方法
    //相当于基于XML AOP中:
    //<aop:pointcut id="save" expression="execution(* com.hk.eshop.anno.RoleMng.saveRole(..))" />
    @Pointcut(value="execution(* com.hk.eshop.anno.RoleMng.saveRole(..))")
    public void saveRole(){};

    //定义空方法
    //相当于基于XML AOP中:
    //<aop:pointcut id="find" expression="execution(* com.hk.eshop.anno.RoleMng.findRole(..))" />
    @Pointcut(value="execution(* com.hk.eshop.anno.RoleMng.findRole(..))")
    public void findRole(){};


    //相当于基于XML AOP中:<aop:before pointcut-ref="saveRole" method="audit"/>
    //					  <aop:before pointcut-ref="findRole" method="audit"/>
    @AfterThrowing(value="saveRole() || findRole()",throwing="throwingValue")
    public void audit(JoinPoint joinPoint, Throwable throwingValue)
    {
        Object [] args = joinPoint.getArgs();
        Signature sgn = joinPoint.getSignature();
        System.out.println("耗时统计开始================================"+sgn.getName());
        for(int i=0;i<args.length;i++)
        {
            System.out.println("第"+(i+1)+"个参数="+args[i]);
        }
        System.out.println("================================耗时统计结束");
        System.out.println("切入点表达式="+joinPoint.toString());
        System.out.println("目标对象方法抛出异常="+throwingValue);
    }
}

package com.hk.eshop.anno;

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

public class Main {
    public static void main( String[] args ) throws Exception
    {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
        System.out.println("#####################最终通知#######################");
        UserMng umng = (UserMng)ctx.getBean("userMng");
        //umng.save("1","Java");
        //umng.find("2");
        System.out.println("#####################环绕通知#######################");

        OrgMng omng = (OrgMng) ctx.getBean("orgMng");
        //omng.save("root", "Java");
        //omng.find("root");

        RoleMng rmng = (RoleMng) ctx.getBean("roleMng");
        rmng.saveRole("admin", "Java");
        rmng.findRole("admin");
    }
}


<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:p="http://www.springframework.org/schema/p"
       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/context
	http://www.springframework.org/schema/context/spring-context-3.0.xsd
	http://www.springframework.org/schema/aop
	http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

    <context:component-scan base-package="com.hk.eshop"/>

    <bean id="userMng" class="com.hk.eshop.anno.UserMng"/>
    <bean id="auditAspect" class="com.hk.eshop.anno.AuditAspect"/>

    <bean id="orgMng" class="com.hk.eshop.anno.OrgMng"/>
    <bean id="logAspect" class="com.hk.eshop.anno.LogAspect"/>

    <bean id="roleMng" class="com.hk.eshop.anno.RoleMng"/>
    <bean id="usedTimeAspect" class="com.hk.eshop.anno.UsedTimeAspect"/>
    <aop:aspectj-autoproxy/>
</beans>
相关推荐
_waylau几秒前
“Java+AI全栈工程师”问答01:Spring MVC登录页面错误提示
java·开发语言·vue.js·后端·spring·mvc·springcloud
Giggle12181 分钟前
上门家政服务平台 | 多端协同,源码交付,用户端小程序+H5、服务端APP、管理后台
java·小程序·架构·产品运营·个人开发
李斯维1 分钟前
工厂设计模式(Factory Pattern):工厂方法与抽象工厂的实例演示
java·设计模式
myloveasuka1 分钟前
通配符 “?“
java
AI人工智能+电脑小能手4 分钟前
【大白话说Java面试题 第41题】【JVM篇】第1题:JVM由哪些部分组成?
java·开发语言·jvm·后端·面试
Lee川5 分钟前
登录注册模块的 JWT 认证机制详解
前端·后端·react.js
0xDevNull6 分钟前
ConcurrentHashMap 与 Hashtable 深度对比
java·开发语言
happymaker06268 分钟前
Spring学习日记——Day01(简单配置使用Spring,手写Spring的简单工厂模式)
java·学习·spring
木易 士心8 分钟前
深度解析:一个 Java 对象究竟占用多少字节?
java·开发语言·后端
夜猫子ing10 分钟前
《嵌入式 Linux 控制服务从零搭建(二):从目录结构到 CMakeLists,搭一个像样的 C++ 工程骨架》
java·前端·c++