本文共 1423 字,大约阅读时间需要 4 分钟。
AspectJ指示器是Spring中使用AOP技术时的重要工具,其作用是确定对哪些对象执行拦截逻辑。了解execution指标符的常用用法是理解AOP配置最直接的方式之一。
execution是最常用的 AspectJ 指示器,它用于配置拦截的具体方法或类。这种指标符非常灵活,能够根据实际需求进行多种配置。以下是execution指标符的一些典型用法示例。
execution(修饰符 返回类型 包名.类名.方法名(参数列表))
例如:
execution(* String com.luckincoffee.example.Test1.test(String))
这个指示表示在com.luckincoffee.example包下的Test1类中,返回类型是String、修饰符不限的方法test(String),也就是所有符合条件的方法都会被拦截。
如果希望拦截包级别的所有方法,可以用'*'表示任意修饰符和返回类型:
execution(* * com.luckincoffee.example.Test1.test(String))
或者用'*'表示任意返回类型:
execution(* * com.luckincoffee.example.Test1.test*(String))
可以用一个'*'表示任意方法名:
execution(* * com.luckincoffee.example.Test1.*(..))
如果需要拦截某个接口及其实现类的全部方法,使用接口名称+.*:
execution(* * com.luckincoffee.example.Test+.*(..))
同时指定类名和特定的方法名,使用特定的字符串格式:
execution(* * com.luckincoffee.example.Test.*To(..))
例如,/TestTo(Shall我理解为Test类中的所有以"to"结尾的方法)。
要拦截特定包下的所有类的特定方法,可以使用".类名",例如:
execution(* * com.luckincoffee.example.*Dao.*(..))
其中,".Dao"表示包名为Dao的所有子包,"(..)"表示所有参数。
execution(* * com.luckincoffee.example.*(..)) 表示com.luckincoffee.example包下的所有类的所有方法,无限制。
参数类型可以通过具体指定来限制:
execution(* * com.luckincoffee.example.Test.*(String))
execution(* * com.luckincoffee.example.Test.*(java.util.List))
execution(* * com.luckincoffee.example.Test.*(Object+))
通过合理配置execution指标符,可以为Spring AOP配置拦截规则,灵活管理应用程序中各部分的业务逻辑。
转载地址:http://ahupz.baihongyu.com/