Spring AOP实例

前言

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);
	}
}

增强功能已实现
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值