文章目录
AOP相关概念
AOP概述
什么是AOP
AOP:即面向切面编程
简单的说就是把我们程序重复的代码抽取出来,在需要执行的时候,使用动态代理技术,在不修改源码的基础上,对我们已有的方法进行增强。
AOP的作用以及优势
- 作用:在程序运行期间,不修改源码对已有方法进行增强。
- 优势:
* 减少重复代码
* 提高开发效率
* 维护方便
AOP的实现方式
使用动态代理即使
AOP的具体应用
案例中的问题
/**
* 账户的业务层实现类
*/
public class AccountServiceImpl implements IAccountService{
private IAccountDao accountDao;
public void setAccountDao(IAccountDao accountDao) {
this.accountDao = accountDao;
}
@Override
public List<Account> findAllAccount() {
return accountDao.findAllAccount();
}
@Override
public Account findAccountById(Integer accountId) {
return accountDao.findAccountById(accountId);
}
@Override
public void saveAccount(Account account) {
accountDao.saveAccount(account);
}
@Override
public void updateAccount(Account account) {
accountDao.updateAccount(account);
}
@Override
public void deleteAccount(Integer acccountId) {
accountDao.deleteAccount(acccountId);
}
}
问题就是:
事务是自动控制的,也就是connection对象是setAutoCommit(true)
此方式控制事务,如果我们每次都执行一条sql语句,没有问题,如果要执行多条语句,一旦多条语句之间抛出异常,那么就会出现问题
问题演示:
在业务层多加入一个方法。
/*
* 业务实现接口
* */
public interface IAccountService {
/**
* 删除
* @param sourceName
* @param targetName
* @param money
*/
void transfer(String sourceName, String targetName, Float money);
}
public class AccountServiceImpl implements IAccountService {
public void transfer(String sourceName, String targetName, Float money) {
//1、根据名称查询两个账户的信息
Account source = iAccountDao.findAccountByName(sourceName);
Account target = iAccountDao.findAccountByName(targetName);
//2、转出账户减钱,转入账户加钱
source.setMoney(source.getMoney() - money);
target.setMoney(target.getMoney() + money);
//3、跟新两个账户
iAccountDao.updateAccount(source);
//模拟异常
int i = 1/0;
iAccountDao.updateAccount(target);
}
}
持久层实现如下
/*
* 持久层接口定义
* */
public interface IAccountDao {
/**
* 删除
* @param acccountId
*/
void deleteAccount(Integer acccountId);
}
public class AccountDaoImpl implements IAccountDao {
public Account findAccountByName(String acccountName) {
try {
List<Account> accounts = runner.query("SELECT * FROM account where name = ?",
new BeanListHandler<Account>(Account.class), acccountName);
if (accounts == null || accounts.size() == 0){
return null;
}
if (accounts.size() > 1){
throw new RuntimeException("只允许有一个返回值");
}
return accounts.get(0);
}catch (SQLException e){
throw new RuntimeException(e);
}
}
}
测试类如下:
@Test
public void testTransfer() {
// //3、执行方法
accountService.transfer("aaa", "bbb", 500f);
}
测试发现数据异常,不符合事务的一致性。
问题的解决
让业务层来控制事务的提交和回滚
- 添加两个工具类
package com.oceanstar.utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
/*
* 连接的工具类,用于从数据源中获取一个连接,并且实现和线程的绑定
* */
@Component
public class ConnectionUtils {
private ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();
@Autowired
private DataSource dataSource;
/*
* 获取当前线程上的连接
* */
public Connection getTheadConnection(){
try {
//1、先从ThreadLocal上获取
Connection connection = threadLocal.get();
//2、判断当前线程上是否有连接
if (connection == null){
//3、从数据源中获取一个连接,并且和当前线程绑定
connection = dataSource.getConnection();
threadLocal.set(connection);
}
//4、返回当前线程上的连接
return connection;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
/*
* 把连接和线程解绑
* */
public void removeConnection(){
threadLocal.remove();
}
}
package com.oceanstar.utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import java.sql.SQLException;
/*
* 和事务管理相关的工具类
* */
@Component
public class TransactionManager {
@Autowired
private ConnectionUtils connectionUtils;
/*
* 开启事务
* */
public void beginTransaction(){
try {
connectionUtils.getTheadConnection().setAutoCommit(false);
} catch (SQLException e) {
e.printStackTrace();
}
}
/*
* 提交事务
* */
public void commit(){
try {
connectionUtils.getTheadConnection().commit();
} catch (SQLException e) {
e.printStackTrace();
}
}
/*
* 回滚事务
* */
public void rollback(){
try {
connectionUtils.getTheadConnection().rollback();
} catch (SQLException e) {
e.printStackTrace();
}
}
/*
* 释放资源
* */
public void release(){
try {
connectionUtils.getTheadConnection().close(); // 还到连接池中
connectionUtils.removeConnection();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
- 改造业务层
package com.oceanstar.service.impl;
import com.oceanstar.dao.IAccountDao;
import com.oceanstar.domain.Account;
import com.oceanstar.service.IAccountService;
import com.oceanstar.utils.TransactionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/*
* 业务实现类
* */
@Service("accountService")
public class AccountServiceImpl implements IAccountService {
@Resource(name = "accountDao")
private IAccountDao iAccountDao;
@Autowired
private TransactionManager transactionManager;
public List<Account> findAllAccount() {
try {
//开启事务
transactionManager.beginTransaction();
// 执行操作
List<Account> accounts = iAccountDao.findAllAccount();
// 提交事务
transactionManager.commit();
//提交结果
return accounts;
}catch (Exception e){
//回滚事务
transactionManager.rollback();
throw new RuntimeException(e);
}finally {
// 释放连接
transactionManager.release();
}
}
public Account findAccountById(Integer acccountId) {
try {
//开启事务
transactionManager.beginTransaction();
// 执行操作
Account accounts = iAccountDao.findAccountById(acccountId);
// 提交事务
transactionManager.commit();
//提交结果
return accounts;
}catch (Exception e){
//回滚事务
transactionManager.rollback();
throw new RuntimeException(e);
}finally {
// 释放连接
transactionManager.release();
}
}
public void saveAccount(Account account) {
try {
//开启事务
transactionManager.beginTransaction();
// 执行操作
iAccountDao.saveAccount(account);
// 提交事务
transactionManager.commit();
}catch (Exception e){
//回滚事务
transactionManager.rollback();
throw new RuntimeException(e);
}finally {
// 释放连接
transactionManager.release();
}
}
public void updateAccount(Account account) {
try {
//开启事务
transactionManager.beginTransaction();
// 执行操作
iAccountDao.updateAccount(account);
// 提交事务
transactionManager.commit();
}catch (Exception e){
//回滚事务
transactionManager.rollback();
throw new RuntimeException(e);
}finally {
// 释放连接
transactionManager.release();
}
}
public void deleteAccount(Integer acccountId) {
try {
//开启事务
transactionManager.beginTransaction();
// 执行操作
iAccountDao.deleteAccount(acccountId);
// 提交事务
transactionManager.commit();
}catch (Exception e){
//回滚事务
transactionManager.rollback();
throw new RuntimeException(e);
}finally {
// 释放连接
transactionManager.release();
}
}
public void transfer(String sourceName, String targetName, Float money) {
try {
//开启事务
transactionManager.beginTransaction();
// 执行操作
//1、根据名称查询两个账户的信息
Account source = iAccountDao.findAccountByName(sourceName);
Account target = iAccountDao.findAccountByName(targetName);
//2、转出账户减钱,转入账户加钱
source.setMoney(source.getMoney() - money);
target.setMoney(target.getMoney() + money);
//3、跟新两个账户
iAccountDao.updateAccount(source);
int i = 1/0;
iAccountDao.updateAccount(target);
// 提交事务
transactionManager.commit();
}catch (Exception e){
//回滚事务
transactionManager.rollback();
throw new RuntimeException(e);
}finally {
// 释放连接
transactionManager.release();
}
}
}
- 改造持久层
package com.oceanstar.dao.impl;
import com.oceanstar.dao.IAccountDao;
import com.oceanstar.domain.Account;
import com.oceanstar.utils.ConnectionUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.sql.SQLException;
import java.util.List;
/*
* 持久层接口实现
* */
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
@Autowired
private QueryRunner runner;
@Autowired
private ConnectionUtils connectionUtils;
public List<Account> findAllAccount() {
try {
return runner.query(connectionUtils.getTheadConnection(),"SELECT * FROM account",
new BeanListHandler<Account>(Account.class));
}catch (SQLException e){
throw new RuntimeException(e);
}
}
public Account findAccountById(Integer acccountId) {
try {
return runner.query(connectionUtils.getTheadConnection(),"SELECT * FROM account where id = ?",
new BeanHandler<Account>(Account.class), acccountId);
}catch (SQLException e){
throw new RuntimeException(e);
}
}
public Account findAccountByName(String acccountName) {
try {
List<Account> accounts = runner.query(connectionUtils.getTheadConnection(),"SELECT * FROM account where name = ?",
new BeanListHandler<Account>(Account.class), acccountName);
if (accounts == null || accounts.size() == 0){
return null;
}
if (accounts.size() > 1){
throw new RuntimeException("只允许有一个返回值");
}
return accounts.get(0);
}catch (SQLException e){
throw new RuntimeException(e);
}
}
public void saveAccount(Account account) {
try {
runner.update(connectionUtils.getTheadConnection(),"insert into account (name, money) values (?, ?)",
account.getName(), account.getMoney());
}catch (SQLException e){
throw new RuntimeException(e);
}
}
public void updateAccount(Account account) {
try {
runner.update(connectionUtils.getTheadConnection(),"update account set name = ? , money = ? where id = ?",
account.getName(), account.getMoney(), account.getId());
}catch (SQLException e){
throw new RuntimeException(e);
}
}
public void deleteAccount(Integer acccountId) {
try {
runner.update(connectionUtils.getTheadConnection(),"delete from account where id = ?", acccountId);
}catch (SQLException e){
throw new RuntimeException(e);
}
}
}
新的问题
上面已经实现了事务控制了,但是也产生了一个新的问题:业务层方法变得臃肿了,里面充斥着许多重复代码。并且业务层和事务控制方法耦合了。
试想一下,如果我们此时提交,回滚,释放资源中任何一个方法名变更,都需要修改业务层的代码,况且这还只是一个业务层实现类,而实际的项目中这种业务层的实现类可能会有几十个
思考:如何解决这个问题。
回答:动态代理技术。
动态代理回顾
动态代理的特点
字节码随用随创建,随用随加载。
它与静态代理的区别也是如此。因为静态代理是字节码一上来就创建好,并完成加载。
动态代理的作用
在不修改源码的前提下,对方法进行增强。
动态代理常用的两种方式
-
基于接口的动态代理:
提供者:JDK官方的Proxy类。 要求:被代理类最少实现一个接口
-
基于子类的动态代理:
提供者:第三方的CGLib 要求:被代理类不能用final修改的类
使用jdk官方的Proxy类创建代理对象
1、新建一个maven工程,不使用骨架。
package com.oceanstar.proxy;
/*
* 经销商选择生产者的标准
* */
public interface IProducer {
/*
* 销售
* */
public void saleProduct(float money);
/*
* 售后
* */
public void afterService(float money);
}
package com.oceanstar.proxy;
/*
* 生产者
* */
public class Producer implements IProducer {
/*
* 销售
* */
public void saleProduct(float money){
System.out.println("挣了" + money + "元, 将产品卖出去");
}
/*
* 售后
* */
public void afterService(float money){
System.out.println("挣了" + money + "元,提供售后服务");
}
}
package com.oceanstar.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/*
* 模拟一个消费者
* */
public class Client {
public static void main(String[] args) {
// 消费者找买家: 直接
final Producer producer = new Producer();
producer.saleProduct(1000);
/*
* 间接代理
* 动态代理:不修改源码的情况下,对方法增强
*
* 基于接口的动态代理:
* 涉及的类: Proxy
* 提供者: JDK官方
*
* 如何创建代理对象:
* 使用 Proxy.newProxyInstance
*
* 创建代理对象的要求:
* 被代理类最少实现一个接口。
*
* newProxyInstance的参数:
*
* ClassLoader : 用于加载代理对象字节码的。和被代理对象使用相同的类加载器。固定写法
* Class<?>[]: 字节码数组---用于让代理对象和被代理对象有相同的方法。固定写法
* InvocationHandler:用于提供增强的代码---如何代理,一般是一个该接口的匿名内部实现类
* 此接口的实现类是谁用谁写
* */
// 代理商
IProducer proxyProducer = (IProducer) Proxy.newProxyInstance(producer.getClass().getClassLoader(),
producer.getClass().getInterfaces(),
new InvocationHandler() {
/*
* 作用:执行该代理对象的任何方法都会经过该方法,此方法有拦截的功能
* @param proxy 代理对象的引用
* @param method 当前执行的方法
* @param args 当前执行方法需要的参数
* @return 和被代理对象有相同的返回值
* @throws
* */
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 提供增强的代码
Object returnValue = null;
//1、获取方法执行的参数
Float money = (Float)args[0];
//2、判断当前方法是不是销售
if("saleProduct".equals(method.getName())){
returnValue = method.invoke(producer, money*0.8f); // 20%给经销商, 80%给生产者
}
return returnValue;
}
});
proxyProducer.saleProduct(1000);
}
}
基于子类的动态代理
1、导入maven的jar坐标
<dependencies>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.1_3</version>
</dependency>
</dependencies>
2、代码实现
package com.oceanstar.cglib;
import com.oceanstar.proxy.IProducer;
/*
* 生产者
* */
public class Producer {
/*
* 销售
* */
public void saleProduct(float money){
System.out.println("挣了" + money + "元, 将产品卖出去");
}
/*
* 售后
* */
public void afterService(float money){
System.out.println("挣了" + money + "元,提供售后服务");
}
}
package com.oceanstar.cglib;
import com.oceanstar.proxy.IProducer;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Enumeration;
/*
* 模拟一个消费者
* */
public class Client {
public static void main(String[] args) {
// 消费者找买家: 直接
final Producer producer = new Producer();
producer.saleProduct(1000);
/*
* 间接代理
* 动态代理:不修改源码的情况下,对方法增强
*
* 基于子类的动态代理:
* 涉及的类: Enhancer
* 提供者: cglib库
*
* 如何创建代理对象:
* 使用 Enhancer.create
*
* 创建代理对象的要求:
* 被代理类不能是最终类
*
* create的参数:
* Class : 用于指定被代理对象的字节码。固定写法
* Callback:用于提供增强的代码---如何代理,一般是该接口的子接口实现类
* */
// 代理商
Producer cglibProducer = (Producer) Enhancer.create(producer.getClass(),
new MethodInterceptor() {
/*
* 作用:执行该代理对象的任何方法都会经过该方法,此方法有拦截的功能
* @param proxy 代理对象的引用
* @param method 当前执行的方法
* @param args 当前执行方法需要的参数
* @param methodProxy:
* @return
* @throws
* */
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
Object returnValue = null;
//1、获取方法执行的参数
Float money = (Float)args[0];
//2、判断当前方法是不是销售
if("saleProduct".equals(method.getName())){
returnValue = method.invoke(producer, money*0.8f); // 20%给经销商, 80%给生产者
}
return returnValue;
}
});
cglibProducer.saleProduct(1000);
}
}
解决案例中的问题:基于动态代理实现事务控制
基于xml的Aop配置
环境搭建
创建工程,并引入jar坐标
1、创建maven工程,不适用骨架
2、修改pom.xml,并引入坐标
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.7</version>
</dependency>
</dependencies>
创建spring的配置文件并导入约束
<?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">
</beans>
编码实现
一般实现
- 业务层
package com.oceanstar;
/*
* 账户的业务层接口
* */
public interface IAccountService {
/*
* 模拟保存账户
* */
void saveAccount();
/*
* 模拟更新账户
* */
void updateAccount(int i);
/*
* 模拟删除账户
* */
int deleteAccount();
}
package com.oceanstar.service.impl;
import com.oceanstar.IAccountService;
public class AccountServiceImpl implements IAccountService {
public void saveAccount() {
System.out.println("保存账户服务");
}
public void updateAccount(int i) {
System.out.println("更新账户" + i);
}
public int deleteAccount() {
System.out.println("删除账户");
return 0;
}
}
- 日志
package com.oceanstar.util;
/*
* 记录日志的工具类
* */
public class Logger {
/**
* 前置通知:在切入点执行之前执行
* */
public void beforeLogging(){
System.out.println("前置通知: 调用Logger的beforeLogging开始记录日志");
}
/**
* 后置通知:在切入点方法正常执行之后执行,和异常通知只能执行一个
* */
public void afterReturning(){
System.out.println("后置通知: 调用Logger的afterReturning开始记录日志");
}
/**
* 异常通知:在切入点方法抛出异常之后执行,和后置通知只能执行一个
* */
public void afterThrowing(){
System.out.println("异常通知: 调用Logger的afterReturning开始记录日志");
}
/**
* 最终通知:无论切入点方法是否正常执行,均会执行
* */
public void afterLogging(){
System.out.println("最终通知: 调用Logger的afterLogging开始记录日志");
}
//
}
- 配置
<?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">
<!--配置spring的Ioc,把service对象配置进来-->
<bean id="accountService" class="com.oceanstar.service.impl.AccountServiceImpl"></bean>
<!--spring中基于xml的APO配置步骤
1、把通知bean也交给spring管理
2、使用aop:config标签表明开始aop配置
3、使用aop:aspect配置切面
id:给切面提供一个唯一标签
ref:指定通知通知类bean的id。
4、使用对应标签来配置通知的类型
aop:before:前置通知
method:用于指定logger类中哪个方法是前置通知。
pointcut: 切入点表达式,表示对业务层的哪些方法增强。
切入点表达式:
关键字:execution()
表达式:
访问修饰符 返回值 包名.包名.包名..类名.方法名(参数类表)
标准写法:
public int com.oceanstar.service.impl.AccountServiceImpl.deleteAccount() // 只增强一个方法
public void com.oceanstar.service.impl.AccountServiceImpl.saveAccount() // 只增强一个方法
public void com.oceanstar.service.impl.AccountServiceImpl.updateAccount(int) // 只增强一个方法
访问修饰符可以省略:
int com.oceanstar.service.impl.AccountServiceImpl.deleteAccount() // 只增强一个方法
void com.oceanstar.service.impl.AccountServiceImpl.saveAccount() // 只增强一个方法
void com.oceanstar.service.impl.AccountServiceImpl.updateAccount(int) // 只增强一个方法
返回值可以使用通配符*代替:
* com.oceanstar.service.impl.AccountServiceImpl.deleteAccount() // 只增强一个方法
* com.oceanstar.service.impl.AccountServiceImpl.saveAccount() // 只增强一个方法
* com.oceanstar.service.impl.AccountServiceImpl.updateAccount(int) // 只增强一个方法
包名可以使用通配符,表示任意包,但是有几级包就要写几个*
* *.*.*.*.AccountServiceImpl.deleteAccount()
包名可以使用..表示当钱包以及其子包
* *..AccountServiceImpl.deleteAccount()
类名和方法名都可以使用*来实现统配
* *..*.deleteAccount()
* *..*.*() // 2个
* *..*.*(int) // 1个
参数类表:
可以直接写数据类型:
基本类型写名称:int
引用类型写包名.类名: java.lang.String
可以使用通配符*表示任意类型,但是必须有参数
可以使用..表示有无参数均可,有参数可以是任意类型
全统配写法
* *..*.*(..)
实际开发中切入点表达式通常写法:
切到业务层实现类下的所有方法:
* com.oceanstar.service.impl.*.*(..)
-->
<!--配置logger类-->
<bean id="logger" class="com.oceanstar.util.Logger"></bean>
<!--配置aop-->
<aop:config>
<!--配置切面-->
<aop:pointcut id="pointcut" expression="execution(void com.oceanstar.service.impl.AccountServiceImpl.saveAccount())"/>
<aop:aspect id="logAdvice" ref="logger">
<!--配置通知的类型,并建立通知方法和切入点方法的关联-->
<aop:before method="beforeLogging" pointcut-ref="pointcut"></aop:before>
<!--后置通知:在切入点方法正常执行之后执行,和异常通知只能执行一个-->
<aop:after-returning method="afterReturning" pointcut-ref="pointcut"></aop:after-returning>
<!--最终通知:在切入点方法抛出异常之后执行,和后置通知只能执行一个-->
<aop:after method="afterLogging" pointcut-ref="pointcut"></aop:after>
<!--异常通知:无论切入点方法是否正常执行,均会执行-->
<aop:after-throwing method="afterThrowing" pointcut-ref="pointcut"></aop:after-throwing>
</aop:aspect>
</aop:config>
</beans>
- 测试
package com.oceanstar.test;
import com.oceanstar.IAccountService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AOPTest {
public static void main(String[] args) {
//1、获取容器
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
//2、获取对象
IAccountService iAccountService = (IAccountService)applicationContext.getBean("accountService");
iAccountService.saveAccount();
// iAccountService.updateAccount(1);
// iAccountService.deleteAccount();
}
}
坏绕通知
- 修改日志类
package com.oceanstar.util;
import org.aspectj.lang.ProceedingJoinPoint;
/*
* 记录日志的工具类
* */
public class Logger {
/*
* 环绕通知:是spring框架为我们提供的一种可以在代码中手动控制增强方法合适执行的方式
* */
public Object aroudLogging(ProceedingJoinPoint proceedingJoinPoint){
Object returnValue = null;
try {
Object[] args = proceedingJoinPoint.getArgs();
System.out.println("前置通知: 调用Logger的aroudLogging开始记录日志");
returnValue = proceedingJoinPoint.proceed(args); // 明确调用业务层方法(切入点方法)
System.out.println("后置通知: 调用Logger的aroudLogging开始记录日志");
return returnValue;
} catch (Throwable throwable) {
System.out.println("异常通知: 调用Logger的aroudLogging开始记录日志");
throw new RuntimeException(throwable);
} finally {
System.out.println("最终通知: 调用Logger的aroudLogging开始记录日志");
}
}
}
- 修改xml文件
<aop:around method="aroudLogging" pointcut-ref="pointcut"></aop:around>
基于注解的AOP配置
环境搭建
创建工程,并引入jar坐标
1、创建maven工程,不适用骨架
2、修改pom.xml,并引入坐标
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.7</version>
</dependency>
</dependencies>
创建spring的配置文件并导入约束
<?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">
</beans>
编程实现
- 业务层
package com.oceanstar;
/*
* 账户的业务层接口
* */
public interface IAccountService {
/*
* 模拟保存账户
* */
void saveAccount();
/*
* 模拟更新账户
* */
void updateAccount(int i);
/*
* 模拟删除账户
* */
int deleteAccount();
}
package com.oceanstar.service.impl;
import com.oceanstar.IAccountService;
import org.springframework.stereotype.Service;
@Service("accountService")
public class AccountServiceImpl implements IAccountService {
public void saveAccount() {
System.out.println("保存账户服务");
}
public void updateAccount(int i) {
System.out.println("更新账户" + i);
}
public int deleteAccount() {
System.out.println("删除账户");
return 0;
}
}
- 日志
package com.oceanstar.util;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
/*
* 记录日志的工具类
* */
@Component("logger")
@Aspect // 表示当前类是一个切面类
public class Logger {
@Pointcut("execution(void com.oceanstar.service.impl.*.*(..))")
private void pointcut(){}
/**
* 前置通知:在切入点执行之前执行
* */
// @Before("pointcut()")
public void beforeLogging(){
System.out.println("前置通知: 调用Logger的beforeLogging开始记录日志");
}
/**
* 后置通知:在切入点方法正常执行之后执行,和异常通知只能执行一个
* */
// @AfterReturning("pointcut()")
public void afterReturning(){
System.out.println("后置通知: 调用Logger的afterReturning开始记录日志");
}
/**
* 异常通知:在切入点方法抛出异常之后执行,和后置通知只能执行一个
* */
// @AfterThrowing("pointcut()")
public void afterThrowing(){
System.out.println("异常通知: 调用Logger的afterReturning开始记录日志");
}
/**
* 最终通知:无论切入点方法是否正常执行,均会执行
* */
// @After("pointcut()")
public void afterLogging(){
System.out.println("最终通知: 调用Logger的afterLogging开始记录日志");
}
/*
* 环绕通知:是spring框架为我们提供的一种可以在代码中手动控制增强方法合适执行的方式
* */
@Around("pointcut()")
public Object aroudLogging(ProceedingJoinPoint proceedingJoinPoint){
Object returnValue = null;
try {
Object[] args = proceedingJoinPoint.getArgs();
System.out.println("前置通知: 调用Logger的aroudLogging开始记录日志");
returnValue = proceedingJoinPoint.proceed(args); // 明确调用业务层方法(切入点方法)
System.out.println("后置通知: 调用Logger的aroudLogging开始记录日志");
return returnValue;
} catch (Throwable throwable) {
System.out.println("异常通知: 调用Logger的aroudLogging开始记录日志");
throw new RuntimeException(throwable);
} finally {
System.out.println("最终通知: 调用Logger的aroudLogging开始记录日志");
}
}
}
- 配置
<?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:context="http://www.springframework.org/schema/context"
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/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--告知spring,在创建容器时要扫描的包-->
<context:component-scan base-package="com.oceanstar"></context:component-scan>
<!--配置spring开启aop的支持-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
- 测试
package com.oceanstar.test;
import com.oceanstar.IAccountService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AOPTest {
public static void main(String[] args) {
//1、获取容器
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
//2、获取对象
IAccountService iAccountService = (IAccountService)applicationContext.getBean("accountService");
iAccountService.saveAccount();
// iAccountService.updateAccount(1);
// iAccountService.deleteAccount();
}
}