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>
相关推荐
Rust研习社几秒前
组合真的优于继承吗?为什么 Rust 和 Go 都拥抱组合舍弃继承?
后端·rust·编程语言
IT_陈寒25 分钟前
JavaScript的闭包把我坑惨了,说好的内存会自动回收呢?
前端·人工智能·后端
CaffeinePro1 小时前
Pydantic深度使用:数据校验、枚举、ORM映射
后端·fastapi
Chenyiax2 小时前
从 Chat 到 Responses:OpenAI API 抽象为什么变了?
后端
MariaH2 小时前
Koa和Express的区别
后端
MariaH2 小时前
Koa框架的使用
后端
luckdewei3 小时前
那个用 passlib 做认证的新同事,上线第一天就把用户密码写进了日志
后端
ping某4 小时前
为什么 Nginx 明明监听了 80,转发后端时却用了 4xxxx 端口?
后端·nginx
JustHappy4 小时前
我汇总了身边朋友的经历才发现,其实第一份实习是最难找的......
前端·后端·面试
uhakadotcom4 小时前
在python 的 工程化架构中 ,什么是 薄包装器层?
后端·面试·github