AspectJ简介
AspectJ(AspectJ官网)是一个AOP的框架,它扩展了Java语言,AspectJ定义了AOP语法,它有一个专门的编译器用来生成遵守Java字节编码规范的Class文件。
AspectJ是AOP在Java中的一种具体实现,且其实现方式更为简洁,使用更为方便,而且还支持注解式开发,所以,Spring又将AspectJ对于AOP的实现也引入到了自己的框架中。
AspectJ的切入点表达式
AspectJ定义了专门的表达式用于指定切入点,表达式的原型为:
execution( [modifiers-pattern] 访问权限类型
ret-type-pattern 返回值类型
[declaring-type-pattern] 全限定性类名
name-pattern(param-pattern) 方法名(参数类型)
[throws-pattern] 抛出异常类型
)
execution 表达式中就是方法的签名。注意,表达式中加[ ]的部分表示可省略部分,各部分间用空格分开。在其中可以使用以下通配符:
符号 | 意义 |
---|---|
* | 表示0至多个任意字符 |
.. | 用在方法参数中,表示任意多个参数 |
..*、*.. | 用在包名后(前),表示当前包及其子包路径 |
+ | 用在类名后,表示当前类及其子类;用在接口后,表示当前接口及其实现类 |
举例说明:
- execution(public * *(..)) :指定切入点为任意公共方法;
- execution(* set*(..)) :指定切入点为任意方法名以“set”开头的公共方法;
- execution(* com.lyj.*.*(..)) :指定切入点为定义在lyj包里的任意类的任意方法(不包含lyj子包下的类);
- execution(* com.lyj..*.*(..)) :指定切入点为定义在lyj包或子包里的任意类的任意方法;
- execution(* *..lyj.*.*(..)) :指定切入点为定义在所有包下的lyj子包里的任意类的任意方法;
AspectJ的开发环境搭建
基于前面的IoC项目(Ioc项目开发环境搭建),还需要下载aspectj-1.9.4.jar包(aspectj-1.9.4.jar下载地址),下载完成之后,解压,并导入lib目录下的aspectjrt.jar、aspectjweaver.jar到项目中,并将jar包添加到项目。
之后,需要向xml配置文件添加xsd约束:
<?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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
</beans>
AspectJ的基于注解的AOP实现
- 定义目标接口
public interface SomeService {
void doSome();
void doOther(int i);
}
- 定义目标类
public class SomeServiceImpl implements SomeService {
@Override
public void doSome() {
System.out.println(