Spring中的Aop简单实例讲解(一个例子让你秒懂)

  • 注重版权,转载请注明原作者和原文链接
    作者:码农BookSea
    原文链接:https://editor.csdn.net/md?articleId=107092569
    在这里插入图片描述

Aop,即面向切面编程,面向切面编程的目标就是分离关注点
比如:一个骑士只需要关注守护安全,或者远征,而骑士辉煌一生的事迹由谁来记录和歌颂呢,当然不会是自己了,这个完全可以由诗人去歌颂,比如当骑士出征的时候诗人可以去欢送,当骑士英勇牺牲的时候,诗人可以写诗歌颂骑士的一生。那么骑士只需要关注怎么打仗就好了。而诗人也只需要关注写诗歌颂和欢送就好了,那么这样就把功能分离了。所以可以把诗人当成一个切面,当骑士出征的前后诗人分别负责欢送和写诗歌颂(记录)。而且,这个切面可以对多个骑士或者明人使用,并不只局限于一个骑士。
这样,既分离了关注点,也减低了代码的复杂程度。

代码示例如下:

骑士类:

package com.cjh.aop2;

/**
 * @author Caijh
 *
 * 2017年7月11日 下午3:53:19
 */
public class BraveKnight {
    
    
 public void saying(){
    
    
 System.out.println("我是骑士");
 }
}

诗人类:

package com.cjh.aop2;

/**
 * @author Caijh
 *
 * 2017年7月11日 下午3:47:04
 */
public class Minstrel {
    
    
 public void beforSay(){
    
    
 System.out.println("前置通知");
 }
 
 public void afterSay(){
    
    
 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 http://www.springframework.org/schema/beans/spring-beans.xsd
 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
 <!-- 目标对象 -->
 <bean id="knight" class="com.cjh.aop2.BraveKnight"/>
 <!-- 切面bean -->
 <bean id="mistrel" class="com.cjh.aop2.Minstrel"/>
 <!-- 面向切面编程 -->
 <aop:config>
 <aop:aspect ref="mistrel">
  <!-- 定义切点 -->
  <aop:pointcut expression="execution(* *.saying(..))" id="embark"/>
  <!-- 声明前置通知 (在切点方法被执行前调用)-->
  <aop:before method="beforSay" pointcut-ref="embark"/>
  <!-- 声明后置通知 (在切点方法被执行后调用)-->
  <aop:after method="afterSay" pointcut-ref="embark"/>
 </aop:aspect>
 </aop:config>
</beans>

测试代码:

package com.cjh.aop2;

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

/**
 * @author Caijh
 *
 * 2017年7月11日 下午4:02:04
 */
public class Test {
    
    
 public static void main(String[] args) {
    
    
 ApplicationContext ac = new ClassPathXmlApplicationContext("com/cjh/aop2/beans.xml");
 BraveKnight br = (BraveKnight) ac.getBean("knight");
 br.saying();
 }
}

执行结果如下:

前置通知
我是骑士
后置通知

=====================================================

aop(面向切面编程)的好处就是,当执行了我们主要关注的行为(骑士类对象),也就是切点,那么切面(诗人对象)就会自动为我们进行服务,无需过多关注。如上测试代码,我们只调用了BraveKnight类的saying()方法,它就自己在saying方法前执行了前置通知方法,在执行完saying之后就自动执行后置通知。通过这样我们可以做权限设置和日志处理。

补充:pointcut执行方法书写格式如下:
在这里插入图片描述
工程目录结构:
在这里插入图片描述
如果运行过程中出现nofoundclass的错误,一般是少了:aspectjweaver.jar这个包,需要下载

以上这篇基于spring中的aop简单实例讲解,这就是今天跟大家分享的内容

老铁,如果有收获,请点个免费的赞鼓励一下博主

白嫖不好,创作不易。各位的点赞就是我创作的最大动力,如果我有哪里写的不对,欢迎评论区留言进行指正,我们下篇文章见!

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/bookssea/article/details/107092569