首页 > 编程语言 >Spring AOP AspectJ 切入点表达式的例子

Spring AOP AspectJ 切入点表达式的例子

时间:2022-11-03 00:24:42浏览次数:68  
标签:log service spring aop studio Spring UserService AOP AspectJ

1) 匹配方法签名模式

最典型的切入点表达式用于匹配的方法签名。

匹配一个类中的所有方法在另一个包

例如,下面的切入点表达式匹配中声明的所有方法 EmployeeManager 接口。 前面的通配符匹配方法与任何修饰符 (public, protected, and private) 和任何返回类型。 两个点的参数列表匹配任意数量的参数。

execution(* com.howtodoinjava.EmployeeManager.*(..))

匹配一个类中的所有方法在同一个包内

如果目标类或接口位于同一个包内你可以省略的包名称。

execution(* EmployeeManager.*(..))

EmployeeManager 匹配所有公共方法

在开始使用公共关键字,使用 * 匹配任何返回类型。

execution(public * EmployeeManager.*(..))

匹配所有公共方法与返回类型 EmployeeDTO EmployeeManager

在开始使用公共关键字和返回类型。

execution(public EmployeeDTO EmployeeManager.*(..))

匹配所有公共方法和返回类型 EmployeeDTO EmployeeManager EmployeeDTO 第一个参数

在开始使用公共关键字和返回类型。 另外,你的第一个参数指定。 其他参数可以通过两个点匹配。

execution(public EmployeeDTO EmployeeManager.*(EmployeeDTO, ..))

匹配所有公共方法与返回类型 EmployeeManager EmployeeDTO 和明确的参数

在开始使用公共关键字和返回类型。 同时,指定所有参数类型。

execution(public EmployeeDTO EmployeeManager.*(EmployeeDTO, Integer))

2) 匹配类型签名模式

当应用于 Spring AOP , 这些切入点的范围将会缩小到匹配中的所有方法执行某些类型。

匹配包 com.howtodoinjava 内部类中定义的所有方法

就像前面的例子。

within(com.howtodoinjava.*)

匹配的类内包 com 中定义的所有方法。 howtodoinjava 和类内所有子包

包括子包使用两个点。

within(com.howtodoinjava..*)

匹配所有方法类在另一个包

就像前一个示例使用执行关键字。

within(com.howtodoinjava.EmployeeManagerImpl)

匹配所有方法与一个类在同一个包

在同一个包,包名称。

within(EmployeeManagerImpl)

匹配所有方法在所有 EmployeeManager 接口的实现类

使用 +(+) 签署的匹配所有实现一个接口。

within(EmployeeManagerImpl+)

3) Bean 名称匹配模式

你也可以匹配所有 bean 有一个常见的命名模式。

匹配所有方法中定义 bean 的名字结尾€˜牵头€™。

Ita€™年代相当简单。 使用一个 * 匹配任何在 bean 的名字前面,然后匹配的单词。

bean(*Manager)

4) 结合切入点表达式

在 AspectJ 切入点表达式可以结合操作符 & &(),| |(或) 和!(不)。 如。

匹配所有方法名称与经理和刀结束

使用€˜| | 一个€™标志结合两个表达式。

bean(*Manager) || bean(*DAO)

 

基于注解的 Spring AOP 的配置和使用  

先来了解一下 AOP 的相关概念,《Spring 参考手册》中定义了以下几个 AOP 的重要概念,结合以上代码分析如下:

  • 切面(Aspect):官 方的抽象定义为 “一个关注点的模块化,这个关注点可能会横切多个对象”,在本例中,“切面” 就是类 TestAspect 所关注的具体行为,例 如,AServiceImpl.barA () 的调用就是切面 TestAspect 所关注的行为之一。“切面” 在 ApplicationContext 中 < aop:aspect > 来配置。
  • 连接点(Joinpoint) :程序执行过程中的某一行为,例如,UserService.get 的调用或者 UserService.delete 抛出异常等行为。
  • 通知(Advice) :“切面” 对于某个 “连接点” 所产生的动作,例如,TestAspect 中对 com.spring.service 包下所有类的方法进行日志记录的动作就是一个 Advice。其中,一个 “切面” 可以包含多个 “Advice”,例如 ServiceAspect。
  • 切入点(Pointcut) :匹配连接点的断言,在 AOP 中通知和一个切入点表达式关联。例如,TestAspect 中的所有通知所关注的连接点,都由切入点表达式 execution (* com.spring.service.*.*(..)) 来决定。
  • 目标对象(Target Object) :被一个或者多个切面所通知的对象。例如,AServcieImpl 和 BServiceImpl,当然在实际运行时,Spring AOP 采用代理实现,实际 AOP 操作的是 TargetObject 的代理对象。
  • AOP 代理(AOP Proxy) : 在 Spring AOP 中有两种代理方式,JDK 动态代理和 CGLIB 代理。默认情况下,TargetObject 实现了接口时,则采用 JDK 动态代理,例 如,AServiceImpl;反之,采用 CGLIB 代理,例如,BServiceImpl。强制使用 CGLIB 代理需要将 <aop:config> 的 proxy-target-class 属性设为 true。

通知(Advice)类型:

  • 前置通知(Before advice):在 某连接点(JoinPoint)之前执行的通知,但这个通知不能阻止连接点前的执行。ApplicationContext 中 在 <aop:aspect> 里面使用 < aop:before > 元素进行声明。例如,TestAspect 中的 doBefore 方 法。
  • 后置通知(After advice):当 某连接点退出的时候执行的通知(不论是正常返回还是异常退出)。ApplicationContext 中在 <aop:aspect> 里面使 用 < aop:after > 元素进行声明。例如,ServiceAspect 中的 returnAfter 方法,所以 Teser 中调用 UserService.delete 抛出异常时,returnAfter 方法仍然执行。
  • 返回后通知(After return advice):在某连接点正常完成后执行的通知,不包括抛出异常的情况。ApplicationContext 中在 <aop:aspect> 里面使用 < after-returning > 元素进行声明。
  • 环绕通知(Around advice):包 围一个连接点的通知,类似 Web 中 Servlet 规范中的 Filter 的 doFilter 方法。可以在方法的调用前后完成自定义的行为,也可以选择不执 行。ApplicationContext 中在 <aop:aspect> 里面使用 < aop:around > 元素进行声明。例 如,ServiceAspect 中的 around 方法。
  • 抛出异常后通知(After throwing advice):在方法抛出异常退出时执行的通知。ApplicationContext 中在 <aop:aspect> 里面使用 < aop:after-throwing > 元素进行声明。例如,ServiceAspect 中的 returnThrow 方法。

使用 Spring AOP 可以基于两种方式,一种是比较方便和强大的注解方式,另一种则是中规中矩的 xml 配置方式。先说注解,使用注解配置 Spring AOP 总体分为两步,第一步是在 xml 文件中声明激活自动扫描组件功能,同时激活自动代理功能(同时在 xml 中添加一个 UserService 的普通服务层组件,来测试 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"
	xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
		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">

	<!-- 激活组件扫描功能,在包cn.ysh.studio.spring.aop及其子包下面自动扫描通过注解配置的组件 -->
	<context:component-scan base-package="cn.ysh.studio.spring.aop"/>
	<!-- 激活自动代理功能 -->
	<aop:aspectj-autoproxy proxy-target-class="true"/>
	<!-- 用户服务对象 -->
	<bean id="userService" class="cn.ysh.studio.spring.aop.service.UserService" />
</beans>

第二步是为 Aspect 切面类添加注解:

package cn.ysh.studio.spring.aop.aspect;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.JoinPoint;
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;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * 系统服务组件Aspect切面Bean
 * @author Shenghany
 * @date 2013-5-28
 */
//声明这是一个组件
@Component
//声明这是一个切面Bean
@Aspect
public class ServiceAspect {

	private final static Log log = LogFactory.getLog(ServiceAspect.class);
	
	//配置切入点,该方法无方法体,主要为方便同类中其他方法使用此处配置的切入点
	@Pointcut("execution(* cn.ysh.studio.spring.aop.service..*(..))")
	public void aspect(){	}
	
	/*
	 * 配置前置通知,使用在方法aspect()上注册的切入点
	 * 同时接受JoinPoint切入点对象,可以没有该参数
	 */
	@Before("aspect()")
	public void before(JoinPoint joinPoint){
		if(log.isInfoEnabled()){
			log.info("before " + joinPoint);
		}
	}
	
	//配置后置通知,使用在方法aspect()上注册的切入点
	@After("aspect()")
	public void after(JoinPoint joinPoint){
		if(log.isInfoEnabled()){
			log.info("after " + joinPoint);
		}
	}
	
	//配置环绕通知,使用在方法aspect()上注册的切入点
	@Around("aspect()")
	public void around(JoinPoint joinPoint){
		long start = System.currentTimeMillis();
		try {
			((ProceedingJoinPoint) joinPoint).proceed();
			long end = System.currentTimeMillis();
			if(log.isInfoEnabled()){
				log.info("around " + joinPoint + "\tUse time : " + (end - start) + " ms!");
			}
		} catch (Throwable e) {
			long end = System.currentTimeMillis();
			if(log.isInfoEnabled()){
				log.info("around " + joinPoint + "\tUse time : " + (end - start) + " ms with exception : " + e.getMessage());
			}
		}
	}
	
	//配置后置返回通知,使用在方法aspect()上注册的切入点
	@AfterReturning("aspect()")
	public void afterReturn(JoinPoint joinPoint){
		if(log.isInfoEnabled()){
			log.info("afterReturn " + joinPoint);
		}
	}
	
	//配置抛出异常后通知,使用在方法aspect()上注册的切入点
	@AfterThrowing(pointcut="aspect()", throwing="ex")
	public void afterThrow(JoinPoint joinPoint, Exception ex){
		if(log.isInfoEnabled()){
			log.info("afterThrow " + joinPoint + "\t" + ex.getMessage());
		}
	}
	
}

测试代码:

package cn.ysh.studio.spring.aop;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.ysh.studio.spring.aop.service.UserService;
import cn.ysh.studio.spring.mvc.bean.User;

/**
 * Spring AOP测试
 * @author Shenghany
 * @date 2013-5-28
 */
public class Tester {

	private final static Log log = LogFactory.getLog(Tester.class);
	
	public static void main(String[] args) {
		//启动Spring容器
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		//获取service组件
		UserService service = (UserService) context.getBean("userService");
		//以普通的方式调用UserService对象的三个方法
		User user = service.get(1L);
		service.save(user);
		try {
			service.delete(1L);
		} catch (Exception e) {
			if(log.isWarnEnabled()){
				log.warn("Delete user : " + e.getMessage());
			}
		}
	}
}

控制台输出如下:

INFO [spring.aop.aspect.ServiceAspect:40] before execution(User cn.ysh.studio.spring.aop.service.UserService.get(long))
 INFO [spring.aop.service.UserService:19] getUser method . . .
 INFO [spring.aop.aspect.ServiceAspect:60] around execution(User cn.ysh.studio.spring.aop.service.UserService.get(long))	Use time : 42 ms!
 INFO [spring.aop.aspect.ServiceAspect:48] after execution(User cn.ysh.studio.spring.aop.service.UserService.get(long))
 INFO [spring.aop.aspect.ServiceAspect:74] afterReturn execution(User cn.ysh.studio.spring.aop.service.UserService.get(long))
 INFO [spring.aop.aspect.ServiceAspect:40] before execution(void cn.ysh.studio.spring.aop.service.UserService.save(User))
 INFO [spring.aop.service.UserService:26] saveUser method . . .
 INFO [spring.aop.aspect.ServiceAspect:60] around execution(void cn.ysh.studio.spring.aop.service.UserService.save(User))	Use time : 2 ms!
 INFO [spring.aop.aspect.ServiceAspect:48] after execution(void cn.ysh.studio.spring.aop.service.UserService.save(User))
 INFO [spring.aop.aspect.ServiceAspect:74] afterReturn execution(void cn.ysh.studio.spring.aop.service.UserService.save(User))
 INFO [spring.aop.aspect.ServiceAspect:40] before execution(boolean cn.ysh.studio.spring.aop.service.UserService.delete(long))
 INFO [spring.aop.service.UserService:32] delete method . . .
 INFO [spring.aop.aspect.ServiceAspect:65] around execution(boolean cn.ysh.studio.spring.aop.service.UserService.delete(long))	Use time : 5 ms with exception : spring aop ThrowAdvice演示
 INFO [spring.aop.aspect.ServiceAspect:48] after execution(boolean cn.ysh.studio.spring.aop.service.UserService.delete(long))
 INFO [spring.aop.aspect.ServiceAspect:74] afterReturn execution(boolean cn.ysh.studio.spring.aop.service.UserService.delete(long))
 WARN [studio.spring.aop.Tester:32] Delete user : Null return value from advice does not match primitive return type for: public boolean cn.ysh.studio.spring.aop.service.UserService.delete(long) throws java.lang.Exception

可以看到,正如我们预期的那样,虽然我们并没有对 UserSerivce 类包括其调用方式做任何改变,但是 Spring 仍然拦截到了其中方法的调用,或许这正是 AOP 的魔力所在。

再简单说一下 xml 配置方式,其实也一样简单:

<?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"
	xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
		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">


	<!-- 系统服务组件的切面Bean -->
	<bean id="serviceAspect" class="cn.ysh.studio.spring.aop.aspect.ServiceAspect"/>
	<!-- AOP配置 -->
	<aop:config>
		<!-- 声明一个切面,并注入切面Bean,相当于@Aspect -->
		<aop:aspect id="simpleAspect" ref="serviceAspect">
			<!-- 配置一个切入点,相当于@Pointcut -->
			<aop:pointcut expression="execution(* cn.ysh.studio.spring.aop.service..*(..))" id="simplePointcut"/>
			<!-- 配置通知,相当于@Before、@After、@AfterReturn、@Around、@AfterThrowing -->
			<aop:before pointcut-ref="simplePointcut" method="before"/>
			<aop:after pointcut-ref="simplePointcut" method="after"/>
			<aop:after-returning pointcut-ref="simplePointcut" method="afterReturn"/>
			<aop:after-throwing pointcut-ref="simplePointcut" method="afterThrow" throwing="ex"/>
		</aop:aspect>
	</aop:config>

</beans>

 

//配置前置通知,拦截返回值为cn.ysh.studio.spring.mvc.bean.User的方法
@Before("execution(cn.ysh.studio.spring.mvc.bean.User cn.ysh.studio.spring.aop.service..*(..))")
public void beforeReturnUser(JoinPoint joinPoint){
	if(log.isInfoEnabled()){
		log.info("beforeReturnUser " + joinPoint);
	}
}

//配置前置通知,拦截参数为cn.ysh.studio.spring.mvc.bean.User的方法
@Before("execution(* cn.ysh.studio.spring.aop.service..*(cn.ysh.studio.spring.mvc.bean.User))")
public void beforeArgUser(JoinPoint joinPoint){
	if(log.isInfoEnabled()){
		log.info("beforeArgUser " + joinPoint);
	}
}

//配置前置通知,拦截含有long类型参数的方法,并将参数值注入到当前方法的形参id中
@Before("aspect()&&args(id)")
public void beforeArgId(JoinPoint joinPoint, long id){
	if(log.isInfoEnabled()){
		log.info("beforeArgId " + joinPoint + "\tID:" + id);
	}
}

 

附上 UserService 的代码 (其实很简单):

package cn.ysh.studio.spring.aop.service;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cn.ysh.studio.spring.mvc.bean.User;

/**
 * 用户服务模型
 * @author Shenghany
 * @date 2013-5-28
 */
public class UserService {

	private final static Log log = LogFactory.getLog(UserService.class);
	
	public User get(long id){
		if(log.isInfoEnabled()){
			log.info("getUser method . . .");
		}
		return new User();
	}
	
	public void save(User user){
		if(log.isInfoEnabled()){
			log.info("saveUser method . . .");
		}
	}
	
	public boolean delete(long id) throws Exception{
		if(log.isInfoEnabled()){
			log.info("delete method . . .");
			throw new Exception("spring aop ThrowAdvice演示");
		}
		return false;
	}
	
}

应该说学习 Spring AOP 有两个难点,第一点在于理解 AOP 的理念和相关概念,第二点在于灵活掌握和使用切入点表达式。概念的理解通常不在一朝一夕,慢慢浸泡的时间长了,自然就明白了,下面我们简单地介绍一下切入点表达式的配置规则吧。

execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern) throws-pattern?) 

 

  • modifiers-pattern:方法的操作权限
  • ret-type-pattern:返回值
  • declaring-type-pattern:方法所在的包
  • name-pattern:方法名
  • parm-pattern:参数名
  • throws-pattern:异常

其 中,除 ret-type-pattern 和 name-pattern 之外,其他都是可选的。上例中,execution (* com.spring.service.*.*(..)) 表示 com.spring.service 包下,返回值为任意类型;方法名任意;参数不作限制的 所有方法。

最后说一下通知参数

可以通过 args 来绑定参数,这样就可以在通知(Advice)中访问具体参数了。例如,<aop:aspect> 配置如下:

<aop:config>
  <aop:aspect id="TestAspect" ref="aspectBean">
   <aop:pointcut id="businessService"
    expression="execution(* com.spring.service.*.*(String,..)) and args(msg,..)" />
    <aop:after pointcut-ref="businessService" method="doAfter"/>
  </aop:aspect>
</aop:config>

上面的代码 args(msg,..) 是指将切入点方法上的第一个 String 类型参数添加到参数名为 msg 的通知的入参上,这样就可以直接使用该参数啦。

访问当前的连接点

在上面的 Aspect 切面 Bean 中已经看到了,每个通知方法第一个参数都是 JoinPoint。其实,在 Spring 中,任何通知(Advice)方法都可以将第一个参数定义为 org.aspectj.lang.JoinPoint 类型用以接受当前连接点对象。JoinPoint 接口提供了一系列有用的方法, 比如 getArgs() (返回方法参数)、getThis() (返回代理对象)、getTarget() (返回目标)、getSignature() (返回正在被通知的方法相关信息)和 toString() (打印出正在被通知的方法的有用信息)。

标签:log,service,spring,aop,studio,Spring,UserService,AOP,AspectJ
From: https://www.cnblogs.com/wangfx/p/16853031.html

相关文章

  • SpringBoot定时任务实现数据同步
    业务的需求是,通过中台调用api接口获得,设备数据,要求现实设备数据的同步。方案一:通过轮询接口的方式执行pullData()方法实现数据同步该方式的原理是先清空之前的所有数据,然......
  • springboot项目整合-注册功能模块开发
    工程简介准备工作:项目所用到的html界面以及sql文件链接如下:链接:https://pan.baidu.com/s/18loHJiKRC6FI6XkoANMSJg?pwd=nkz2提取码:nkz2复制这段内容后打开百度网盘......
  • SpringBoot高级篇MongoDB之查询基本使用姿势
    学习一个新的数据库,一般怎么下手呢?基本的CURD没跑了,当可以熟练的增、删、改、查一个数据库时,可以说对这个数据库算是入门了,如果需要更进一步的话,就需要了解下数据库的特性,比......
  • SpringBoot文件上传异常之temporary upload location not valid
    SpringBoot搭建的应用,一直工作得好好的,突然发现上传文件失败,提示​​org.springframework.web.multipart.MultipartException:Failedtoparsemultipartservletrequest;......
  • 【Java】开始学习Spring Boot了,你不来瞅一眼?
    (开始学习SpringBoot了,你不来瞅一眼)SpringBoot是什么?做一名Java开发程序员必须要知道的开发利器——SpringBoot。在JavaEE领域,SpringBoot在传统Spring框架的基......
  • SpringBoot + Mybatis系列之插件机制 Interceptor
    【SpringBoot+Mybatis系列】插件机制Interceptor在Mybatis中,插件机制提供了非常强大的扩展能力,在sql最终执行之前,提供了四个拦截点,支持不同场景的功能扩展Executor(......
  • [springboot, lettuce] io.lettuce.core.RedisCommandTimeoutException: Command time
    https://blog.csdn.net/zzhongcy/article/details/118935350?spm=1001.2101.3001.6650.7&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFr......
  • 2.什么是SpringMVC
    2.什么是SpringMVC概述:  SpringMVC是SpringFramework的一部分,是基于Java实现MVC的轻量级Web框架官方文档:https://docs.spring.io/spring/docs/5.2.0.RELEASE/spri......
  • SpringBoot笔记:集成MyBatis
    SpringBoot中使用MyBatis与MVC中本质是一样的,只是某些配置可以直接使用注解完成,使编码更加便捷了。1.pom依赖集成MyBatis通常需要MyBatis、Spring、数据库驱动三个依赖,......
  • SpringMVC源码-创建FormattingConversionServiceFactoryBean
    一、FormattingConversionServiceFactoryBeanFormattingConversionServiceFactoryBean实现了FactoryBean接口,可以通过getObject获取ConversionService。FormattingConver......