这次的博客一样采用全注解进行配置,东西也比较简单
首先说明,SpringAop需要有aspectjweaver这个依赖,要先加入到maven中;
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.8</version>
</dependency>
其次,对于进行增强的方法,需要将其所在类加入到ioc容器中,如下:
@Component
public class HelloWorld {
public void sayHello (){
System.out.println("Hello World!");
}
}
接下来需要声明切面,切点,通知,一样需要在spring的ioc容器内,且需要@Aspect注解,
@Aspect是让spring对该进行aop扫描,这样才能扫描到该类内部的切点、通知的注解,如下:
@Aspect
@Component
public class HelloWorldAspect {
@Pointcut(value = "execution(* aop..sayHello(..))")
public void pointCut (){
}
@Before(value = "pointCut()")
private void beforeAdvice (){
System.out.println("===========before advice param:");
}
@After( value = "pointCut()")
private void afterAdvice (){
System.out.println("===========after advice param:");
}
@Around(value = "pointCut()")
private void aroundAdvice (ProceedingJoinPoint pjp) throws Throwable{
System.out.println("===========before advice param: around");
pjp.proceed();
System.out.println("===========after advice param: around");
}
}
这样一来,我们就完成了切点匹配,前置、后知、环绕通知的声明,然后就可以进行测试了
测试代码如下:
@Test
public void testAop (){
ApplicationContext ctx = new AnnotationConfigApplicationContext(AopConfig.class);
HelloWorld hw = ctx.getBean(HelloWorld.class);
hw.sayHello();
}
输出的结果如下:
===========before advice param: around
===========before advice param:
Hello World!
===========after advice param: around
===========after advice param:
所以我们得到结果:
前置时 环绕通知 -> 前置通知
后置时 环绕通知 -> 后置通知
另外spring中还有@AfterReturning、@AfterThrowing,这些将在下一次再写了,如果想早点看的话,可以参考下面的这个链接:
http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle