【问题标题】:Restricting access to static methds with ArchUnit使用 ArchUnit 限制对静态方法的访问
【发布时间】:2021-06-04 11:54:42
【问题描述】:

在我们的架构指南中,我们应该只从域模型或存储库实现(位于基础架构层)中实例化业务异常

我们通常使用工厂方法创建异常。

所以我想为此制定一个 ArchUnit 规则。应该遵循以下原则: 只有位于domainRepositories 的实现的类才能大声调用带有@BusinessException 注释的类的静态方法

我们所有的业务异常都使用@BusinessException 进行注释。所以很容易找到它们。

我尝试了它的变体:

 noClasses().that().resideOutsideOfPackages(DOMAIN).or(areImplementing(Repository.class))
                .should().callMethodWhere(
                target(owner(isAnnotatedWith(BusinessException.class)))
                        .and(target(modifier(JavaModifier.STATIC))));

areImplementing() 是一个自定义谓词,用于确定一个类是否是存储库的实现。

此代码无法编译。 isAnnotatedWith不能这样用。

我也尝试过

methods().that().areStatic()
              .and().areDeclaredInClassesThat().areAnnotatedWith(BusinessException.class)
              .should().onlyBeCalled().byClassesThat(areImplementing(Repository.class))

同样,这不会编译,onlyBeCalled 不存在。

有人有想法吗?

【问题讨论】:

    标签: java archunit


    【解决方案1】:

    我不完全确定是否有更短的形式来表达你想要的,但我相信以下使用自定义谓词的 sn-p 可以完成这项工作。

    noClasses().that()
                // Restriction applies to all classes outside DOMAIN package that are not Repository classes
                .resideOutsideOfPackages(DOMAIN)
                .and()
                .areNotAssignableFrom(Repository.class)
                .should()
                .callMethodWhere(describe("static methods in BusinessExceptions",
                                  // Target method may not reside in class annotated with BusinessException
                    methodCall -> methodCall.getTarget().getOwner().isAnnotatedWith(BusinessException.class) 
                           // And target method may not have the static modifier
                        && methodCall.getTarget()
                            .resolve()
                            .stream()
                            .anyMatch(m -> m.getModifiers().contains(JavaModifier.STATIC))));
    
    

    我唯一不确定的是 methodCall.getTarget().resolve() 返回一组 JavaMethod 类。

    【讨论】:

      猜你喜欢
      • 2014-08-04
      • 1970-01-01
      • 1970-01-01
      • 2019-11-17
      • 1970-01-01
      • 1970-01-01
      • 2011-08-06
      • 2012-02-15
      • 2021-09-08
      相关资源
      最近更新 更多