三种方式使用spring实现AOP(实际上以后要自己单独写aop的机会也不会太多,但是也要了解Spring的aop)
第二种方式——自定义类 相对来说这种用的多点,文档中好多用这种方式
需要导入Spring AOP api的依赖jar包,可以在老的Spring lib(如2.5)里面找到
aopalliance.jar
aspectjweaver.jar
在beans.xml里面需要导入aop的命名空间并在XML catalog里面配置好
切面不用实现任何接口
public class Log{
public void before(){
System.out.println("------方法执行前--------");
}
public void after(){
System.out.println("------方法执行后--------");
}
}
beans.xml
<bean id="userService" class="cn.sxt.service.UserServiceImpl"></bean>
<bean id="log" class="cn.sxt.log.Log"></bean>
<aop:config>
<aop:aspect ref="log">
<aop:pointcut expression="execution(* cn.sxt.service.*.*(.. ))" id="pointcut"/>
<aop:before method="before" pointcut-ref="pointcut"/>
<aop:after method="after" pointcut-ref="pointcut"/>
</aop:aspect>
</aop:config>
配置文件解析:
<aop:config>
里面
<aop:aspect ref="log">
ref引用了通知对象
<aop:pointcut expression="execution(* cn.sxt.service.*.*(.. ))" id="pointcut"/>
表示横切点
<aop:before method="before" pointcut-ref="pointcut"/>
前置通知 通知对象里的方法 横切点引用