Spring基础-AOP

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 {
}
运行结果

运行结果

  • 4
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 14
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值