Spring AOP注解快速入门
1、引入spring坐标、aspectj坐标、junit坐标、spring-test坐标
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.3</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
2、编写接口类
public interface TargetInterface {
public void doSomething();
}
3、编写接口实现类
@Component("targetInterfaceImpl")
public class TargetInterfaceImpl implements TargetInterface {
public void doSomething() {
System.out.println("doSomething running......");
}
}
4、编写切面类
@Component("aspect")
@org.aspectj.lang.annotation.Aspect//标注该类为一个切面类
public class Aspect {
//配置前置通知
// @Before("Aspect.pointcut()") //第一种写法
@Before("pointcut()") //第二种写法
public void before(){
System.out.println("前置增强");
}
@Pointcut("execution(public void com.itheima.aop.*.*(..))")
public void pointcut(){}
}
5、配置applicationContext.xml
1)引入context命名空间和aop命令空间
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
2)开启组件扫描和aop自动代理
<!--开启组件扫描-->
<context:component-scan base-package="com.itheima"/>
<!--aop自动代理-->
<aop:aspectj-autoproxy/>
6、代码测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Test {
@Autowired
private TargetInterface targetInterface;
@org.junit.Test
public void testAop(){
targetInterface.doSomething();
}
}
7、遇到的问题
如果采用切点表达式的抽取的方式定义切点表达式可能会出现
Caused by: java.lang.IllegalArgumentException: error at ::0 can't find referenced pointcut pointcut
但是如果不采用切点表达式的抽取,则不会报错
@Before("execution(public void com.itheima.aop.*.*(..))")
这可能是由于aspectj的版本导致的,
本人在使用1.8.4时报错,将版本修改为1.9.4则不报错