Spring 学习六 之一 Spring-AOP 注解开发示例

  • 需要一个Aspect 的类,在类上添加注解 @Aspect
package com.john.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.JoinPoint.StaticPart;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import com.john.service.LimintConfigService;

@Component
@Aspect
public class LoggerAspect {

    @Pointcut(value ="execution(* com.john.service.LimintConfigService.*(..))")
    public void pointCut() {

    }

    @Before(value = "pointCut()")
    public void beforeAdvice() {
        System.out.println("before advice...");    
    }

    @After(value = "pointCut()")
    public void afterAdvice() {
        System.out.println("after advice...");
    }

    @AfterReturning(value = "pointCut()")
    public void returningAdvice() {
        System.out.println("returning advice...");
    }

    @AfterThrowing(value = "pointCut()")
    public void throwAdvice() {
        System.out.println("throw advice...");
    }

    @Around(value = "pointCut()")
    public void aroundAdvice() {
        System.out.println("around advice...");
    }
}
  • 业务逻辑类,在调用业务方法before()时,LoggerAspect 相应的通知,会切入到before()中,执行通知
@Service
public class LimintConfigService {

    public void before() {
        System.out.println("before()");
    }
}
  • 主配置类,简化了,这里主要测试 AOP 功能,所有简化了很多,一定要开启 aspect 功能,在配置类上面加注解 @EnableAspectJAutoProxy
@Configuration
@EnableAspectJAutoProxy
@ComponentScan(basePackages = {"com.john"})
public class MainConfig {

}
  • 测试
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfig.class);
        
        LimintConfigService service = context.getBean(LimintConfigService.class);
        service.after();     
          
        context.close();
    }
  • 执行结果,测试时,本人_屏蔽了 aroundAdvice()_ 通知
    执行结果
    接下来,将详细讲解
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值