还不理解springAOP?来吧,带你学习spring的面向切面编程(第一篇)

2022-07-26,,,,

首先AOP是指面向切面编程,是OOP(面向对象编程)的补充。那么什么是切面(Aspect)呢,就是切点(pointcut)和通知(advice)的结合使用,什么是通知?通知定义了切面要做什么,在什么时候做,而切点则定义了在什么地方做,将两者结合在一起就可以解释切面是在何时何地做什么功能。

举一个例子,如果你要保存一个账户信息,但在执行保存操作之前还想打印一条日志,那控制日志打印和保存账户的信息就构成了一个切面。打印日志,在什么时候打印就是通知,而在什么地方执行保存操作就是切点,这两者构成了切面。

spring的AOP是基于动态代理实现的,为什么这么说呢,因为保存账户和打印日志两个单独的操作,需要AOP控制它们执行的时机。

案例如下:

接口:

package cn.com.lzxh.service;
/**
 * 业务层接口
 * spring的AOP是基于动态代理实现的。
 * */
public interface AccountService {

	void saveAccount();
}

实现类:

package cn.com.lzxh.service.impl;

import cn.com.lzxh.service.AccountService;

public class AccountServiceImpl implements AccountService {

	@Override
	public void saveAccount() {
		System.out.println("保存数据。。。");
	}

}

日志类:

package cn.com.lzxh.utils;

public class Logger {

	public void printLog() {
		System.out.println("在切入点方法执行之前,开始打印日志。。。");
	}
}

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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">
        
        <bean id="accountService" class="cn.com.lzxh.service.impl.AccountServiceImpl"></bean>
        
        <!-- 注册日志bean -->
        <bean id="logger" class="cn.com.lzxh.utils.Logger"></bean>
        
        <!-- 配置AOP -->
        <aop:config>
        	<!-- 配置切面 -->
        	<aop:aspect id="aspect" ref="logger">
        		<!-- 
        			before:代表前置通知,
        			method:代表通知所执行的方法
        			pointcut:代表切入点执行的方法
        		 -->
        		<aop:before method="printLog" pointcut="execution(public void cn.com.lzxh.service.impl.AccountServiceImpl.saveAccount())"/>
        	</aop:aspect>
        </aop:config>
        <!-- 加入以下配置,防止spring AOP代理混用导致异常 -->
        <aop:aspectj-autoproxy proxy-target-class="true"/>
        
</beans>

在这里需要注意,前置通知就是在切点方法执行的通知。

测试类:

package cn.com.lzxh.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.com.lzxh.service.AccountService;
import cn.com.lzxh.service.impl.AccountServiceImpl;

public class TestAOP {

	public static void main(String[] args) {
		ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
		AccountService as = ac.getBean("accountService", AccountServiceImpl.class);
		as.saveAccount();
	}

}

运行结果:

 

以上就是一个完整的springAOP的例子。

本文地址:https://blog.csdn.net/qq_25816185/article/details/110881472

《还不理解springAOP?来吧,带你学习spring的面向切面编程(第一篇).doc》

下载本文的Word格式文档,以方便收藏与打印。