Spring的AOP,即面向切面编程。aop,一般用于公共的代码的设置,比如日志记录、事务处理等,下面以日记记录为例,简单介绍下,如何配置aop。项目代码已放入GitHub上:https://github.com/qiuxinfa/spring-study。注解版AOP点这里。
1.pom.xml在原有的基础上,添加aspectj依赖:
<!--添加aop依赖aspectj-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
2.创建一个业务类:PersonServiceImpl.java
public class PersonServiceImpl{
public void addPerson() {
System.out.println("------- addPerson() --------");
}
public void getPerson() {
System.out.println("------- getPerson() --------");
}
}
3.创建一个切面类:LogAop.java
public class LogAop {
public void logBefore(){
System.out.println("方法开始,记录日志。。。");
}
public void logAfter(){
System.out.println("方法结束,记录日志。。。");
}
}
4.配置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"
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">
<!--创建目标类,注意:class是实现类的全限定类名,不是接口的,因为接口不能实例化-->
<bean id="personServiceImpl" class="com.qxf.service.impl.PersonServiceImpl"></bean>
<!--创建切面类,这里就是配置日志了 -->
<bean id="myLog" class="com.qxf.aop.LogAop"></bean>
<!--配置aop,关于切入点表达式:
第一个*:表示 任意修饰符 任意返回值
第二个*:表示 任意方法
参数列表中的2个点:表示 任意参数
合起来就是:PersonServiceImpl类中所有方法
-->
<aop:config>
<!-- 切入点表达式 -->
<aop:pointcut expression="execution(* com.qxf.service.impl.PersonServiceImpl.*(..))" id="myPointCut"/>
<aop:aspect ref="myLog">
<!-- 配置前置通知,注意 method 的值要和 对应切面的类方法名称相同 -->
<aop:before method="logBefore" pointcut-ref="myPointCut"></aop:before>
<!-- 配置后置通知,注意 method 的值要和 对应切面的类方法名称相同 -->
<aop:after-returning method="logAfter" pointcut-ref="myPointCut"/>
</aop:aspect>
</aop:config>
</beans>
5.测试
(1)测试代码
public class AopTest {
public static void main(String[] args) {
//加载配置文件,启动容器
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//从容器中获取bean
PersonServiceImpl personService = context.getBean("personServiceImpl", PersonServiceImpl.class);
personService.addPerson();
personService.getPerson();
//关闭容器
context.close();
}
}
(2)测试结果
可以看到,每个方法调用前后,都会执行公共的代码,进行日志记录,这就是aop了。