准备jar包
定义目标类
1. 目标类接口
public interface ITarger {
public void HelloWorld();
}
2. 目标类的实现
public class TargetImpl implements ITarger{
public void HelloWorld(){
System.out.println("hello world");
}
}
3. 定义切面支持类
切面支持类提供了通知的实现
public class HelloWorldAspect {
//前置通知
public void before(){
System.out.println("this is before");
}
//后置通知
public void after(){
System.out.println("this is after");
}
}
在 XML 中配置切面
<?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-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<!-- 配置bean -->
<bean id="HelloWorld" class="com.target.TargetImpl"></bean>
<!-- 配置切面 -->
<bean id="HelloWorldAspect" class="com.aspect.HelloWorldAspect"></bean>
<aop:config proxy-target-class="true">
<aop:pointcut expression="execution(* com.target.TargetImpl.*(..))"
id="HelloWorldPointcut" />
<aop:aspect ref="HelloWorldAspect">
<aop:before pointcut-ref="HelloWorldPointcut" method="before" />
<aop:after pointcut-ref="HelloWorldPointcut" method="after" />
</aop:aspect>
</aop:config>
</beans>
切面的详细解读
以上就是切面的所有详细配置信息。
aop:pointcut 声明了切点,execution 指定了切点将指向哪个连接点(关于execution上一篇文章有很详细说明,这里不多赘述)
Spring AOP 之 通知、连接点、切点、切面。
aop:aspect 中 ref 引入了切面支持类的Bean;aop:before 表示定义前置通知,pointcut-ref 引入切点,method 定义了引用切面辅助类中的哪个方法去执行前置通知。
好啦,就是这么简单啦,如果哪里我没有说清楚,请留言回复我哦。
接下来我们看下执行结果。
在 helloworld 执行前首先执行了前置通知,输出了 this is before;
helloworld执行完成后又去执行了后置通知,输出了this is after;
本文介绍了一个使用Spring AOP实现的简单示例。通过定义目标类和切面支持类,在XML中进行配置,实现了前置和后置通知的功能。具体包括目标接口ITarger、实现类TargetImpl及切面支持类HelloWorldAspect的定义。
168万+

被折叠的 条评论
为什么被折叠?



