添加依赖
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.4</version>
</dependency>
<?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 http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--目标对象-->
<bean class="com.aop.Target" id="target"/>
<!--切面对象-->
<bean class="com.aop.MyAspect" id="myAspect"/>
<!--配置织入 告诉spring哪些切点需要进行哪些增强-->
<aop:config>
<!--声明切面:切点(Target.save())+通知(myAspect.before())-->
<aop:aspect ref="myAspect">
<aop:before method="before" pointcut="execution(public void com.aop.Target.save())" />
</aop:aspect>
</aop:config>
</beans>
切点表达式
execution(public void com.aop.Target.save()
execution([修饰符] 返回值 包.类.方法(参数))
1。 返回值、包、类、方法都可以用*表示任意
2。包后一个 ’ . ’ 代表此包下的所有类,后边两个点’.'代表此包和其自包下的所有类 。
3。参数列表可以用两个点.代表任意类型任意数量的参数。
junit测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:Config.xml")
public class aopTest {
@Autowired
private TargetInterface target;
@Test
public void test1(){
target.save();
}
}
结果
更多通知。
结果:
异常抛出通知在save里使用 除数=0.
结果:
但不知道为啥最终增强这个位置在其他增强前面
切点表达式的抽取:
将切点变成bean,在织入时用ref 指定这个切点就行,好处是降低切点的修改成本。