zoukankan      html  css  js  c++  java
  • 从C#到Java(Aspect)

    1.pom.xml中导入依赖

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-aop</artifactId>
            </dependency>
    

    2.创建class,并加入注解

    @Aspect
    @Component
    @Slf4j
    public class PayChannelAspect {
        private final String POINT_CUT = "execution(public * com.xx.xx.xx.service.xxService.*(..))";
    
        @Autowired
        private AppConfiguration appConfiguration;
    
    
        @Around(POINT_CUT)
        public Object doInvoke(ProceedingJoinPoint joinPoint) throws Throwable {
            var appId = Arrays.stream(joinPoint.getArgs()).findFirst().orElse("N");
            if (appId.equals("N")) {
                log.error("参数未传");
                return BaseResult.fail("参数未传");
            }
            var wxOpen = appConfiguration.getWx().equals("Y") ? true : false;
            var aliOpen = appConfiguration.getAli().equals("Y") ? true : false;
            if (!wxOpen) {
                if (appId.equals(appConfiguration.getWxAppId())
                        || appId.equals(appConfiguration.getMpAppId())) {
                    log.info("微信支付通道已经关闭,参数:" + joinPoint.getArgs());
                    return BaseResult.fail("微信支付通道已经关闭");
                }
            }
            if (!aliOpen) {
                if (appId.equals(appConfiguration.getAliAppId())) {
                    log.info("支付宝支付通道已经关闭,参数:" + joinPoint.getArgs());
                    return BaseResult.fail("支付宝支付通道已经关闭");
                }
            }
            return joinPoint.proceed();
        }
    }
    

    aspect包含四个注解,@Before,@After,@AfterReturning,@Around

      @Before  方法执行前

      @After 方法执行后,返回前

      @Afterreturning 方法返回

      @Around 环绕,从切面首先进入@Around -> @Before -> Method -> @Around -> @After -> @AfterReturning

    如果有多个Aop切面拦截,需要在类上加入注解:@Order

  • 相关阅读:
    php设计模式之桥接模式
    php设计模式适配器模式
    php设计模式之装饰器模式
    php设计模式之策略模式
    php设计模式之责任链模式
    Graphics.DrawString 方法
    算法7-10:拓扑排序
    一年成为Emacs高手(像神一样使用编辑器)
    动态规划0—1背包问题
    辛星解读为什么PHP须要模板
  • 原文地址:https://www.cnblogs.com/LvJiaXuanBlogs/p/10495432.html
Copyright © 2011-2022 走看看