前言
Spring AOP:面向切面编程
通过动态代理的方式对原有代码功能进行**“按需增强”**
应用场景:权限控制、异常处理、缓存、事务管理、日志记录、数据校验等等
目录
一、“原有功能”类
GoodService.java
public interface GoodService {
public void deleteById(int id);
}
GoodServiceImpl.java
public class GoodServiceImpl implements GoodService {
@Override
public void deleteById(int id) {
System.out.println("执行SQL语句,删除**");
}
}
二、“增强功能”类
TransactionAdvice.java
public class TransactionAdvice {
public void start() {
System.out.println("开启事务");
}
public void stop() {
System.out.println("关闭事务");
}
}
三、配置文件
spring.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"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 有哪些要被用到的类,进行实例化 -->
<bean id="goodService" class="com.zk.spring.service.impl.GoodServiceImpl"></bean>
<bean id="advice" class="com.zk.spring.advice.TransactionAdvice"></bean>
<!-- aop配置 -->
<aop:config>
<!-- 设置aspect 设置切面,功能增强 -->
<aop:aspect ref="advice">
<!-- 功能增强的具体逻辑,以及切面的位置 -->
<!-- 切面的配置 -->
<aop:pointcut expression="execution(* com.zk.spring.service.impl.*.*(..))" id="serviceCut"/>
<!-- 在切面被执行前,调用aop before标签 -->
<aop:before method="start" pointcut-ref="serviceCut"/>
<!-- 在切面被执行后,调用aop after标签 -->
<aop:after method="stop" pointcut-ref="serviceCut"/>
</aop:aspect>
</aop:config>
</beans>
四、测试
TestGoodAdvice.java
public class TestGoodAdvice {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
GoodService goodService = (GoodService) context.getBean("goodService");
goodService.deleteById(1);
}
}
增强功能已实现