Spring框架之面向切面编程AOP(3.0)

Spring框架之面向切面编程AOP(3.0)

基于Annotation的AOP配置

虽然在开发过程之中,90%的情况下对于AOP的控制基本上都是基于配置文件完成的,当然AOP本身为了方便代码的编写,也可以使用Annotation进行控制;
1,修改applicationContext配置文件:

<?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:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="
		http://www.springframework.org/schema/aop 
		http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
		http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context-4.1.xsd">
	<context:annotation-config />
	<context:component-scan base-package="cn.mldn" />
	<aop:aspectj-autoproxy/> 
</beans>

2,修改SreviceProxy程序配置,让其变为Aonntation注解配置:

package cn.mldn.aop;

import java.util.Arrays;

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.springframework.stereotype.Component;
@Aspect 
@Component
public class ServiceProxy {
	@Before(value="execution(* cn.mldn.service..*.*(..)) and args(id)",argNames="id")
	public void beforeMethod(Object obj) {
   System.out.println("####### 【ServiceProxy】public void beforeMethod(){},参数内容:" + obj);
	} 
	@After(value="execution(* cn.mldn.service..*.*(..))")
	public void afterMethod() {
	System.out.println("####### 【ServiceProxy】public void afterMethod(){}");
	}
	@AfterReturning(value="execution(* cn.mldn.service..*.*(..))",returning="v",argNames="v")
	public void returnMethod(Object val) {	// 处理返回值
	System.out.println("####### 【ServiceProxy】public void returnMethod(){},返回值:" + val);
	}
	@AfterThrowing(value="execution(* cn.mldn.service..*.*(..))",throwing="e",argNames="e")
	public void throwMethod(Exception e) {	// 对异常进行处理
	System.out.println("####### 【ServiceProxy】public void throwMethod(){},异常信息:" + e);
	} 
	@Around(value="execution(* cn.mldn.service..*.*(..))")
	public Object aroundMethod(ProceedingJoinPoint point) throws Throwable {	// 调用具体的执行方法
	System.out.println("@@@@@ 【环绕通知】aroundMethod() - before,参数:" + Arrays.toString(point.getArgs()));	// 取得所有传递过来的参数
		// 此时可以针对于参数接收后处理后再传递的操作
	Object obj = point.proceed(new Object [] {"abc"}) ;	// 自己来处理内容
	System.out.println("@@@@@ 【环绕通知】aroundMethod() - after,返回结果:" + obj);
	return true ;	// 不按照结果返回数据
	}
} 

3,运行结果:
在这里插入图片描述

发布了28 篇原创文章 · 获赞 1 · 访问量 1702
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章