在 Java 中实施分层架构 [英] Enforcing layered architecture in Java

查看:21
本文介绍了在 Java 中实施分层架构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设一个用Java编写的软件系统由三层组成,A -> B -> C,即A层使用B层,B层使用C层.

Given a software system written in Java consisting of three layers, A -> B -> C, i.e. layer A uses layer B and B uses layer C.

我想确保一层的类只能访问同一层的类或其直接依赖,即 B 应该能够访问 C 而不能访问 A.A 也应该能够访问 B 但不是 C.

I want to make sure that a class of one layer only has access only to classes of the same layer or its direct dependency, i.e. B should be able to access C but not A. Also A should be able to access B but not C.

是否有一种简单的方法可以强制执行此类限制?理想情况下,如果有人试图访问错误层的类,我希望 eclipse 立即抱怨.

Is there an easy way to enforce such a restriction? Ideally I want eclipse to complain at once if one tries to access a class of the wrong layer.

软件目前使用maven.因此,我尝试将 A、B 和 C 放入不同的 maven 模块并正确声明依赖项.这可以很好地阻止 B 访问 A,但不能阻止 A 访问 C.

The software currently uses maven. Therefore I tried to put A, B, and C into different maven modules and to declare dependencies properly. This works fine to prevent B to access A, but does not prevent A to access C.

接下来我尝试从对 B 的依赖中排除 C.这现在也阻止了从 A 到 C 的访问.但是现在我不再能够使用复制依赖来收集运行时所需的所有传递依赖.

Next I tried to exclude C from the dependency to B. This now also prevents access from A to C. However now I am no longer able to use copy-dependencies to collect all transitive dependencies needed for run time.

有没有一种好的方法可以让我清晰地分离层,同时还可以让我收集所有需要的运行时依赖项?

Is there a good way that allows me a clean separation of layers, but also allows me to collect all needed runtime dependencies?

推荐答案

也许你可以在A的pom里试试这个:

Maybe you can try this in the pom of A:

<dependency>
    <groupId>the.groupId</groupId>
    <artifactId>moduleB</artifactId>
    <version>1.0</version>
    <exclusions>
        <exclusion>
            <groupId>the.groupId</groupId>
            <artifactId>moduleC</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>the.groupId</groupId>
    <artifactId>moduleC</artifactId>
    <version>1.0</version>
    <scope>runtime</scope>
</dependency>

这对您有帮助吗?

这篇关于在 Java 中实施分层架构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆