AOP

  • AOP:面向切面编程
  • Spring 的Aop是为了解耦。弥补OOP的不足。
  • Spring支持Aspect J的注解式切面编程
    1. 使用@Aspect是一个切面
    2. 使用@After、@Before、@Around定义建言,可直接将拦截规则作为参数。
    3. @After、@Before、@Around参数的拦截规则则为切点,为了复用,可使用@PointCut定义拦截规则,然后在@After、@Before、@Around的参数中调用
    4. 符合条件的每一个被拦截处为连接点(JoinPoint)
使用注解的被拦截类
package ch1.aop;

import org.springframework.stereotype.Service;

/**
 * 编写使用注解的被拦截类
 */
@Service
public class DemoAnnotationService {
    @Action( name="注解式拦截的add操作")
    public void add(){}
}
使用方法规则被拦截类
package ch1.aop;

import org.springframework.stereotype.Service;

/**
 * 编写使用方法规则被拦截类
 */
@Service
public class DemoMethodService {
    public void add(){}
}
切面
package ch1.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect // 通过@Aspect 注解声明一个切面
@Component // 通过@Component 让此切面成为Spring容器管理的Bean
public class LogAspect {
    @Pointcut("@annotation(ch1.aop.Action)") // 声明切点
    public void annotationPontCut(){};

    @After("annotationPontCut()") // 声明一个建言,并使用@PointCut 定义的切点
    public void after(JoinPoint joinPoint){
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Action action = method.getAnnotation(Action.class);
        System.out.println("注解式拦截:" + action.name()); //通过反射可获得注解上的属性
    }

    @Before("execution(* ch1.aop.DemoMethodService.*(..))") // 声明一个建言,直接使用拦截规则作为参数
    public void before(JoinPoint joinPoint){
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        Method method = signature.getMethod();
        System.out.println("方法规则式拦截。"+method.getName());
    }
}
配置类
package ch1.aop;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@Configuration
@ComponentScan("ch1.aop")
@EnableAspectJAutoProxy // 开始Spring对AspectJ的支持
public class AopConfig {
}
运行结果

运行结果

posted on 2021-05-10 22:06  NE_STOP  阅读(1)  评论(0编辑  收藏  举报  来源