Annotation方式
首先需要在spring的配置文件applicationContext.xml中引入xml的命名空间以及schemaLocation,如下所示:
xmlns:aop="http://www.springframework.org/schema/aop"
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
注意一点的就是,如果在spring中用到aop方面的内容,还需要引入相应的jar包。
之后,就需要在xml文件中加入如下一句代码:
<aop:aspectj-autoproxy />
这样spring就可以自动产生代理,并对相应的注解进行解读。
建立一个日志记录类:
LogInterceptor.java
package com.bd.aop;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class LogInterceptor {
@Before(value="execution(public void com.bd.dao.impl.UserDaoImpl.add(..))")
public void before(){
System.out.println("method start!!!");
}
}
这样程序运行add()方法时,就会先运行这个逻辑,程序运行结果如下:
解释:@Aspect:意思这个类为切面类。
@Component:因为作为切面类需要spring管理起来,所以在初始化时就需要将这个类初始化并交给spring管理
@Before:切入点逻辑
Execution:切入点语法
这里还可以换一种写法:
LogInterceptor.java
package com.bd.aop;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class LogInterceptor {
@Pointcut(value="execution(public * com.bd.dao..*.*(..))")
public void myMethod(){
}
@Before(value="myMethod()")
public void before(){
System.out.println("before start!");
}
@After(value="myMethod()")
public void after(){
System.out.println("after start!");
}
}
运行结果为:
解释:@Pointcut表示切入点的集合,比如在这里,定义了多个切入点。那么在执行方法 的时候就可以执行多个逻辑。
XML配置
首先需要明确一点就是,关于XML配置需要好好的了解一下,最好掌握此种配置方法。
第一步,还是和上面的一样,引入xml命名空间以及schemaLocation;
相关配置如下:
<aop:config>
<aop:aspect id="serviceAspect" ref="logInterceptor">
<aop:pointcut expression="execution(public * com.bd.service..*.*(..))" id="myPointcut"/>
<aop:before method="before" pointcut-ref="myPointcut"/>
<aop:after method="after" pointcut-ref="myPointcut"/>
</aop:aspect>
</aop:config>
其实和annotation配置逻辑实现差不多,首先定义一个切面类,之后定义切入点的集合,然后再配置需要的方法(advice)。
同时,也可以这样配置:
<aop:config>
<aop:aspect id="serviceAspect" ref="logInterceptor">
<aop:before method="before" pointcut="execution(public * com.bd.service..*.*(..))"/>
<aop:after method="after" pointcut="execution(public * com.bd.service..*.*(..))"/>
</aop:aspect>
</aop:config>
两者所表达的效果也是一样的,同样这也是说明了切入点的集合的作用。定义好了之后,直接进行引用就可以了。
同时,对于上面的配置需要注意的一个地方就是,定义切面类的时候,是用到了IOC的注解。@Component(value="logInterceptor"),这样在配置此切面类的时候,才可以直接进行引用。