spring --(16)AOP前置通知与后置通知

AspectJ是目前最流行的AOP框架。
本例采用注解的方式实现前置通知,xml配置方式稍后讲解
//接口

public interface Calculator {
	int add(int i,int j);
	int sub(int i,int j);
}

//接口实现类

@Component
public class CalculatorImpl implements Calculator{

	@Override
	public int add(int i, int j) {
		int result = i+j;
		return result;
	}

	@Override
	public int sub(int i, int j) {
		int result = i-j;
		return result;
	}

}

//切面类

package com.test.aop.impl;

import java.util.Arrays;
import java.util.List;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

/**
 * 切面类
 * 1.需要将该类放入到IOC容器中
 * 2.再将它申明为一个切面
 */
@Aspect
@Component
public class LoggingAspect {
	
	//声明该方法是一个前置通知
	//在如下方法开始执行之前执行
	@Before("execution(public int com.test.aop.impl.CalculatorImpl.add(int, int))")
	public void beforeMethod(JoinPoint joinPoint) {
		//获取方法名
		String methodName = joinPoint.getSignature().getName();
		//获取方法参数
		List<Object> args = Arrays.asList(joinPoint.getArgs());
		System.out.println("The method" + methodName + "begin"+args);
	}

	//后置通知
	//目标方法执行之后(无论是否发生异常),执行的通知
	@After("execution(* com.test.aop.impl.CalculatorImpl.*(int,int))")
	public void afterMethod(JoinPoint joinPoint) {
		//获取方法名
		String methodName = joinPoint.getSignature().getName();
		System.out.println("The method" + methodName + "end");
	}
}

//main方法

public class Main {
	
	@SuppressWarnings("resource")
	public static void main(String[] args) {
		ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
		Calculator calculator = ctx.getBean(Calculator.class);
		int result = calculator.add(1, 2);
		System.out.println(result);
	}
}

//xml配置文件

	<!-- 自动扫描包 -->
	<context:component-scan base-package="com.test.aop.impl"></context:component-scan>
	
	<!-- 使AspectJ注解起作用,为匹配的类生成代理对象 -->
	<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

//输出结果

The methodaddbegin[1, 2]
The methodaddend
3

转载于:https://my.oschina.net/u/2312022/blog/740510

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值