【Spring AOP】基于AspectJ的AOP基本使用

什么是AspectJ?

Spring在2.0后对AOP功能进行了重要增强,主要表现在以下几个方面:
  • 新增了基于Schema的配置支持,提供了aop命名空间;
  • 新增了对AspectJ切点表达式的支持,它通过JDK注解功能,允许开发者在POJO类中定义切面,当然由于Spring只支持方法级的切点,所以对@AspectJ提供了有限的支持;
  • 可以无缝集成AspectJ。

怎么使用AspectJ配置AOP?

先通过一个demo来看一下,还是以之前举得例子来说明,如下:
定义一个AspectJ切面
@Aspect
public class PreGreetingAspect {

	@Before("execution(* greetTo(..))")
	public void beforeGreeting(){
		System.out.println("How are you!");
	}
}
通过@Aspect注解将PreGreetingAspect定义为一个切面,@Before注解定义增强类型和切点,同时beforeGreeting()方法实现了增强的逻辑。

然后我们通过AspectJProxyFactory为Waiter生成一个织入PreGreetingAspect切面的代理,如下:

public class AspectJProxyTest {

	public static void main(String[] args) {
		Waiter waiter = new Waiter();
		AspectJProxyFactory factory = new AspectJProxyFactory();
		factory.setTarget(waiter);
		factory.addAspect(PreGreetingAspect.class);
		Waiter proxy = factory.getProxy();
		proxy.greetTo("John");
	}
}

如何通过spring的配置方式使用@AspectJ切面

第一种方式使用AnnotationAwareAspectJAutoProxyCreator来自动装配AspectJ切面到目标类:
<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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
	<!-- 目标bean -->
	<bean id="waiter" class="com.zheng.demo2.Waiter"></bean>
	<!-- aspectJ切面 -->
	<bean id="preGreetingAspect" class="com.zheng.demo2.PreGreetingAspect"></bean>
	<!-- 自动代理创建器,自动将AspectJ切面编织到目标Bean中 -->
	<bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator"></bean>
</beans>
第二种通过spring的aop命名空间,这个更简单了:
<?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:aop="http://www.springframework.org/schema/aop" 
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
	http://www.springframework.org/schema/aop 
     http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
	
	<!-- aop自动扫描AspectJ切面的驱动 -->
	<aop:aspectj-autoproxy/>
	<!-- 目标bean -->
	<bean id="waiter" class="com.zheng.demo2.Waiter"></bean>
	<!-- aspectJ切面 -->
	<bean id="preGreetingAspect" class="com.zheng.demo2.PreGreetingAspect"></bean>
</beans>
不过需要注意的是<aop:aspectj-autoproxy/>标签有一个proxy-target-class属性,默认为false,使用的是JDK动态代理技术,设置true时使用CGLib动态代理技术,不过如果目标类没有声明接口,spring会自动使用CGLib动态代理。


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值