温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

基于spring中的aop简单实例讲解

发布时间:2020-10-22 08:19:01 来源:脚本之家 阅读:185 作者:jingxian 栏目:编程语言

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执行方法书写格式如下

基于spring中的aop简单实例讲解

工程目录结构:

基于spring中的aop简单实例讲解

如果运行过程中出现nofoundclass的错误,一般是少了:aspectjweaver.jar这个包,需要下载

以上这篇基于spring中的aop简单实例讲解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI