嘿,小伙伴,上一篇我们一起学习了 XML 方式创建切面。看到了那么感到烦吧,这一次给你整个简单地玩玩。那就是使用注解方式创建切面。
@AspectJ
使用注解来创建切面是 AspectJ 5 引入的关键特性。AspectJ 面向注解模型可以非常简单的通过少量注解把任意类转换为切面。这种新特性通常称为 @AspectJ。
在上一篇 Spring AOP 之 实现切点、切面 中,我们通过 XML 方式实现切面,下面我们要通过注解方式实现上一篇中的功能。
通过注解方式实现切面 & 切点
package com.aspect;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
@Aspect()
public class HelloWorldAspect {
@Pointcut("execution(* com.target.TargetImpl.*(..))")
public void pointcutName(){
}
//前置通知
public void before(value="pointcutName()"){
System.out.println("this is before");
}
//后置通知
public void after(value="pointcutName()"){
System.out.println("this is after");
}
}
@Aspect 注解进行了标注,该注解标识了 HelloWorld 不仅仅是一个 POJO,还可以是一个切面。
@Pointcut 注解用于定义一个可以在 @Aspect 切面内可重用的切点。@Ponitcut 注解的值是一个 AdpectJ 切点表达式。
HelloWorldAspect中的方法是用注解标注。@Before()表示为前置通知、@after() 表示为后置通知。其余通知类型也可以用注解表示
@Pointcut 标注的方法则会将方法名作为切点名称,用于通知方法应该应用在哪里。
这样就采用注解方式定义了切面,切点,通知。接下来就是通知 Spring 的配置文件,在 Spring 中声明自动代理 Bean ,该 Bean 知道如何把 @AspectJ 注解所标注的 Bean 转换为代理通知。
<aop:aspectj-autoproxy/>
然后将切面文件注册称为 Sping Bean 进行管理
<bean id="HelloWorldAspect" class="com.aspect.HelloWorldAspect"></bean>
以下是完整的 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"
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-autoproxy/>
<aop:config proxy-target-class="true"/>
<!-- 配置bean -->
<bean id="HelloWorld" class="com.target.TargetImpl"></bean>
<bean id="HelloWorldAspect" class="com.aspect.HelloWorldAspect"></bean>
</beans>
好了,到这里就完成了注解方式配置切面了,我们运行下
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.target.TargetImpl;
public class Test_AOP {
@Test
public void Test_HelloWordAop(){
ApplicationContext context = new ClassPathXmlApplicationContext("HelloWorldAspect.xml");
TargetImpl target = context.getBean("HelloWorld",TargetImpl.class);
target.HelloWorld();
}
}
ok Spring已经将前置通知和后置通知都注入HelloWorld()方法中了。到这里就真正完成啦。
回顾与总结
第一步:创建切面辅助类。并使用 @Aspect( ) 将类标注为切面
第二步:创建切点方法,该方法必须为 void 返回值类型,可以不进行实现。并采用 @Pointcut 方式进行标注为切点。
第三步:采用 @Before、@After、@AfterThrowing 等等进行定义通知类型。
第四步:运行测试。