Spring : AspectJ

spring AOP就是用AspectJ来实现的,是依赖关系!AspectJ是动态代理的一种实现!spring默认使用的就是AspectJ来实现的动态代理,spring自己的AOP就是使用AspectJ来实现的!

AspectJ是一个面向切面的框架,它扩展了Java语言。AspectJ定义了AOP语法(如:execution(* com.springinaction.springidol.Thinker.thinkofsomething(String)) && args


(thoughts)))所以它有一个专门的编译器用来生成遵守Java字节编码规范的Class文件。

AspectJ配置详解:

<?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-2.5.xsd
           http://www.springframework.org/schema/aop 
           http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">

		<!-- 启动对@AspectJ注解的支持  -->  
        <aop:aspectj-autoproxy />    
</beans>  


 

注解切面:
@Aspect
public class MyInterceptor {
	@Pointcut("execution (* cn.itcast.service.impl.PersonServiceBean.*(..))")
	private void anyMethod() {}//声明一个切点,anyMethod无任何意义,只是供注解依附
	
	@Before("anyMethod() && args(name)")
	public void doAccessCheck(String name) {
		System.out.println("前置通知:"+ name);
	}
	@AfterReturning(pointcut="anyMethod()",returning="result")
	public void doAfterReturning(String result) {
		System.out.println("后置通知:"+ result);
	}
	@After("anyMethod()")
	public void doAfter() {
		System.out.println("最终通知");
	}
	@AfterThrowing(pointcut="anyMethod()",throwing="e")
	public void doAfterThrowing(Exception e) {
		System.out.println("例外通知:"+ e);
	}
	
	//环绕通知
	@Around("anyMethod()")
	public Object doBasicProfiling(ProceedingJoinPoint joinpoint) throws Throwable {
		System.out.println("进入方法");
		Object result = joinpoint.proceed();
		System.out.println("退出方法");
		return result;
	}
}


 

传递参数给所标注的通知
@Aspect
public class Magician implements MindReader{
	private String thoughts;

	//设置切点参数类型String 和参数thoughts
	@Pointcut("execution(* com.springinaction.springidol.Thinker.thinkofsomething(String)) && args(thoughts)")
	public void thinking(String thoughts){
	}

	@Before("Thinking(thoughts)")//拦截切点的参数
	public void interceptThoughts(String thoughts){
		this.thoughts = thoughts;
	}

	public String getThoughts(){
		return thoughts;
	}
}


 

用注解给切点添加新功能:
@Aspect
public class ContestantIntroducer{
	
	@DeclareParents(
		value="com.springinaction.springidol.Performer+",
		defaultImpl=GraciousContestant.class)
	public static Contestant contestant;
}

Performer是切点,GraciousContestant是新增功能,contestant是接口,GraciousContestant是实现

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值