Spring_9 Spring基于AspectJ AOP 注解实

2017-09-21  本文已影响67人  mm_cuckoo

Spring AOP 使用注解方式增强

配置spring.xml文件

  1. 在 spring.xml 中开启AOP注解。
  2. 在 spring.xml 中实例增强类和被增强(也可使用注解)
    开启注入配置方法:
<aop:aspectj-autoproxy/>
<?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.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
 
    <!-- 1. 开启 AOP 自动代理(注解) -->
    <aop:aspectj-autoproxy/>
    
    <!-- 2. 实例化对象 -->
    <bean id="book" class="com.sfox.spring.aop.Book"/>
    <bean id="myBook" class="com.sfox.spring.aop.MyBook"/>
    
</beans>

被增强的实体

package com.sfox.spring.aop;

public class Book {
    public void add(){
        System.out.println("被增强的方法.......");
    }
}

增强的实体

package com.sfox.spring.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

//设置增强类
@Aspect
public class MyBook {
    //设置前置增强
    @Before(value="execution(* com.sfox.spring.aop.Book.*(..))")
    public void befor(){
        System.out.println("注解前置增强......");
    }
    
    @After(value="execution(* com.sfox.spring.aop.Book.*(..))")
    public void after(){
        System.out.println("注解后置增强......");
    }
    
    @Around(value="execution(* com.sfox.spring.aop.Book.*(..))")
    public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
        System.out.println("注解运行方法后.....");
        proceedingJoinPoint.proceed();
        System.out.println("注解运行方法后.....");
    }
}

注解说明:

  1. @Aspect : 设置增强类
  2. @Before(value="表达式") : 前置增强
  3. @After(value="表达式") : 后置增强
  4. @Around(value="表达式") : 环绕增强

运行结果

注解运行方法后.....
注解前置增强......
被增强的方法.......
注解运行方法后.....
注解后置增强......
上一篇 下一篇

猜你喜欢

热点阅读