You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ArchUnit如何修改规则允许非SQL出站包访问指定豁免JPA类

ArchUnit规则修改方案

原规则问题

原规则采用一刀切逻辑,禁止所有..infrastructure.outbound.sql..包外的类访问javax.persistence..、org.hibernate..包下的任意类,导致核心服务层捕获PersistenceException并调用其方法的合法逻辑被误判为架构违规。

修改后规则

你只需要在被访问类的匹配条件中,追加排除PersistenceException及其子类的判断即可,修改后代码如下:

import com.tngtech.archunit.junit.ArchTest;
import com.tngtech.archunit.lang.ArchRule;

import javax.persistence.PersistenceException;

import static com.tngtech.archunit.base.DescribedPredicate.not;
import static com.tngtech.archunit.core.domain.JavaClass.Predicates.assignableTo;
import static com.tngtech.archunit.core.domain.JavaClass.Predicates.resideInAnyPackage;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;

@ArchTest
ArchRule only_sql_adapter_pull_jpa_dependencies =
    noClasses().that().resideOutsideOfPackage("..infrastructure.outbound.sql..")
        .should().accessClassesThat(
            resideInAnyPackage("javax.persistence..", "org.hibernate..")
                .and(not(assignableTo(PersistenceException.class)))
        );

规则逻辑说明

  • 原有包范围限制完全保留:仅..infrastructure.outbound.sql..包下的类可以无限制访问JPA/Hibernate相关类
  • 新增的排除逻辑会放行所有对PersistenceException及其子类的访问,覆盖你代码中捕获异常、调用异常实例getMessage()等方法的场景,不会再产生误报
  • assignableTo匹配逻辑会同时覆盖异常类本身、所有继承自该异常的子类,后续如果有自定义的JPA异常子类需要在核心层捕获,也会自动被规则放行

内容的提问来源于stack exchange,提问作者Zartc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 22:06:22