步骤:
1.导入坐标
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.4</version>
</dependency>
2.创建目标类和接口(内部有切点)
public interface TargetInterface {
public void save();
}
@Component
public class Target implements TargetInterface{
public void save() {
System.out.println("save running....");
}
}
3.创建切面类(内部有增强方法)
@Component
@Aspect //标注当前aspect是切面类
public class MyAspect {
//配置织入关系 value=切点表达式
@Before(value = "execution(public void com.hao.anno.Target.save())")
public void before(){
System.out.println("前置增强...");
}
public void afterReturning(){
System.out.println("后置增强...");
}
public Object around(ProceedingJoinPoint point) throws Throwable { //切入点
System.out.println("环绕前增强...");
//切点方法
Object proceed = point.proceed();
System.out.println("环绕后增强...");
return proceed;
}
}
4.将目标类和切面类的对象创建权交给spring
5.在切面类中使用注解配置织入关系
第三步和第二步已经实现
6.在配置文件中开启组件扫描和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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
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">
<!-- 组件扫描-->
<context:component-scan base-package="com.hao.anno"></context:component-scan>
<!-- aop自动代理-->
<aop:aspectj-autoproxy/>
</beans>
7.测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContextanno.xml")
public class AnnoTest {
@Autowired
private TargetInterface target;
@Test
public void test2(){
target.save();
}
}
结果:
前置增强…
save running…