spring aop实例讲解_Spring Framework

spring aop实例讲解_Spring Framework在上篇博文中,我向大家介绍了Aop重要概念和教程,这回给出代码示例。一、XML方式1.TestAspect:切面类packagecom.spring.aop;importorg.aspectj.lang.JoinPoint;importorg.aspectj.lang.ProceedingJoinPoint;publicclassTestAspect{ pu

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺

在上篇博文中,我向大家介绍了Aop重要概念和教程,这回给出代码示例。

一、XML方式

1. TestAspect:切面类

package com.spring.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;

public class TestAspect {

	public void doAfter(JoinPoint jp) {
		System.out.println("log Ending method: " + jp.getTarget().getClass().getName() + "." + jp.getSignature().getName());
	}

	public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
		long time = System.currentTimeMillis();
		Object retVal = pjp.proceed();
		time = System.currentTimeMillis() - time;
		System.out.println("process time: " + time + " ms");
		return retVal;
	}

	public void doBefore(JoinPoint jp) {
		System.out.println("log Begining method: " + jp.getTarget().getClass().getName() + "." + jp.getSignature().getName());
	}

	public void doThrowing(JoinPoint jp, Throwable ex) {
		System.out.println("method " + jp.getTarget().getClass().getName() + "." + jp.getSignature().getName() + " throw exception");
		System.out.println(ex.getMessage());
	}
}

2. AServiceImpl:目标对象

package com.spring.service;

// 使用jdk动态代理
public class AServiceImpl implements AService {

	public void barA() {
		System.out.println("AServiceImpl.barA()");
	}

	public void fooA(String _msg) {
		System.out.println("AServiceImpl.fooA(msg:" + _msg + ")");
	}
}

3. BServiceImpl:目标对象

package com.spring.service;

// 使用cglib
public class BServiceImpl {

	public void barB(String _msg, int _type) {
		System.out.println("BServiceImpl.barB(msg:" + _msg + " type:" + _type + ")");
		if (_type == 1)
			throw new IllegalArgumentException("测试异常");
	}

	public void fooB() {
		System.out.println("BServiceImpl.fooB()");
	}

}

4. ApplicationContext: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"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
    <aop:config>
        <aop:aspect id="TestAspect" ref="aspectBean">
            <!--配置com.spring.service包下所有类或接口的所有方法-->
            <aop:pointcut id="businessService" expression="execution(* com.spring.service.*.*(..))" />
            <aop:before pointcut-ref="businessService" method="doBefore"/>
            <aop:after pointcut-ref="businessService" method="doAfter"/>
            <aop:around pointcut-ref="businessService" method="doAround"/>
            <aop:after-throwing pointcut-ref="businessService" method="doThrowing" throwing="ex"/>
        </aop:aspect>
    </aop:config>
    
    <bean id="aspectBean" class="com.spring.aop.TestAspect" />
    <bean id="aService" class="com.spring.service.AServiceImpl"></bean>
    <bean id="bService" class="com.spring.service.BServiceImpl"></bean>
</beans>

 

二、注解(Annotation)方式

1. TestAnnotationAspect

package com.spring.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class TestAnnotationAspect {

	@Pointcut("execution(* com.spring.service.*.*(..))")
	private void pointCutMethod() {
	}

	//声明前置通知
	@Before("pointCutMethod()")
	public void doBefore() {
		System.out.println("前置通知");
	}

	//声明后置通知
	@AfterReturning(pointcut = "pointCutMethod()", returning = "result")
	public void doAfterReturning(String result) {
		System.out.println("后置通知");
		System.out.println("---" + result + "---");
	}

	//声明例外通知
	@AfterThrowing(pointcut = "pointCutMethod()", throwing = "e")
	public void doAfterThrowing(Exception e) {
		System.out.println("例外通知");
		System.out.println(e.getMessage());
	}

	//声明最终通知
	@After("pointCutMethod()")
	public void doAfter() {
		System.out.println("最终通知");
	}

	//声明环绕通知
	@Around("pointCutMethod()")
	public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
		System.out.println("进入方法---环绕通知");
		Object o = pjp.proceed();
		System.out.println("退出方法---环绕通知");
		return o;
	}
}

2. ApplicationContext: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"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
    <bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator" />

    <bean id="aspectBean" class="com.spring.aop.TestAnnotationAspect" />
    <bean id="aService" class="com.spring.service.AServiceImpl"></bean>
    <bean id="bService" class="com.spring.service.BServiceImpl"></bean>
</beans>

 

关于切入点表达式,大家需要好好练习才能深入理解其中含义。即使看的懂,但是写起来却非常麻烦,并没有想象中那么简单。

最后,再告诉大家:

任何通知(Advice)方法可以将第一个参数定义为 org.aspectj.lang.JoinPoint类型。JoinPoint接口提供了一系列有用的方法, 比如 getArgs() (返回方法参数)、getThis() (返回代理对象)、getTarget() (返回目标)、getSignature() (返回正在被通知的方法相关信息)和 toString() (打印出正在被通知的方法的有用信息。

其中getSignature()返回的Signature对象可强制转换为MethodSignature,其功能非常强大,能获取包括参数名称在内的一切方法信息。

 

============友情链接============

Spring Aop详尽教程 http://blog.csdn.net/wangpeng047/article/details/8556800

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/169620.html原文链接:https://javaforall.net

赞 (0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 传真服务器的定义与选购

    传真服务器的定义与选购 AOFAX热点:传真服务器的定义与选购服务信息卡:联系人:朱成军服务热线:15920885998 商务QQ:909075483.一、传真服务器和传真系统传真服务器定义:所谓传真服务器,就是为企业内部所有员工提供电脑传真收发服务的设备,能够长期脱离其他电脑独立工作,是传真服务器的必要条件。传真服务器由传真软件、传真卡、工控机等组成。传真系统:传真服务器在某些场合也

    2022年6月28日
  • linux文件共享 samba_文件共享服务

    linux文件共享 samba_文件共享服务Samba是在Linux和UNIX系统上实现SMB协议的一个免费软件,由服务器及客户端程序构成;SMB(ServerMessagesBlock,信息服务块)是一种在局域网上共享文件和打印机的一种通信协议,它为局域网内的不同计算机之间提供文件及打印机等资源的共享服务;SMB协议是客户机/服务器型协议,客户机通过该协议可以访问服务器上的共享文件系统,

    2022年9月24日
  • 金蝶erp管理系统下载_erp 金蝶

    金蝶erp管理系统下载_erp 金蝶源码说明:超强的工作流系统,强大的可视化工作流编辑器,灵活自定义表单设计,充分实现企业基于工作流的各项业务管理,与其他模块数据(如HRM等)完美结合。全面综合的任务系统,实现基于信息录入、单据管理、业务协作、工作流转、任务提醒、统计分析等的智能管理。所有单据均支持上传附件功能;且报价单、销售合同、采购订单、发货出库、入库单、派工单等所有模板均支持自定义编辑打印。集成功能实用的CRM系统、进…

    2022年9月16日
  • 基于RGBD的slam_rgb算法

    基于RGBD的slam_rgb算法一.引言  首先,我们需要知道什么是SLAM(simultaneous localization and mapping, 详见SlamCN),SLAM,即时定位与制图,包含3个关键词:实时、定位、制图,就是实时完成定位和制图的任务,这就是SLAM要解决的基本任务。按照使用的传感器分为激光SLAM(LOAM、V-LOAM、cartographer)与视觉SLAM,其中视觉SLAM又可分为单

    2022年9月18日
  • python hashlib_Python hashlib模块实例使用详解

    python hashlib_Python hashlib模块实例使用详解这篇文章主要介绍了Pythonhashlib模块实例使用详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下hashlib模块主要的作用:加密保护消息安全,常用的加密算法如MD5,SHA1等。1、查看可用的算法有哪些hashlib_algorithms.py#!/usr/bin/envpython#-*-coding:utf-8-*-i…

    2022年6月6日
  • conda查看及添加镜像源「建议收藏」

    conda查看及添加镜像源「建议收藏」查看源condaconfig–show-sources添加仓库condaconfig–addchannelshttps://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/condaconfig–addchannelshttps://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/condaconfig–setshow_channel_urlsyes..

    2022年10月1日

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号