ArchUnit允许我们使用exceptions()方法来排除子包中的特定包或类。例如,假设我们有一个应用程序包含名为“com.example”的包,其中包含名为“com.example.service”的子包,我们想要检查应用程序中是否存在违反架构规则的类,但不想在“com.example.service”或其子包中查找这些违规的类。我们可以使用以下代码进行排除:
@ArchTest
public static final ArchRule no_classes_should_access_service_layer =
noClasses()
.should().dependOnClassesThat()
.resideInAnyPackage("com.example.service..")
.because("Services should only be accessed via their interfaces or implementation.");
在这个例子中,我们使用了resideInAnyPackage()方法来指定我们不想要检查的包。“com.example.service..”用双点号来表示除“com.example.service”以外的所有子包。这将防止检查“com.example.service”包及其所有子包中的所有类。使用exceptions()方法也可以完成这个功能,但是使用resideInAnyPackage()方法可以更方便地指定多个排除包。
@ArchTest
public static final ArchRule no_classes_should_access_service_layer =
noClasses()
.should().dependOnClassesThat()
.resideInAnyPackage("com.example..")
.and(dont(
resideInAnyPackage("..service..")
).because("Services should only be accessed via their interfaces or implementation.");
在这个例子中,我们使用dont()方法来排除“..service..”中的子包。dont()方法是ArchUnit的另一种方法来排除类和包。