How should I structure a Java application, where do I put my classes?

后端 未结 10 1340
轻奢々
轻奢々 2020-12-24 05:17

First of all, I know how to build a Java application. But I have always been puzzled about where to put my classes. There are proponents for organizing the packages in a str

10条回答
  •  醉梦人生
    2020-12-24 06:17

    I've really come to like Maven's Standard Directory Layout.

    One of the key ideas for me is to have two source roots - one for production code and one for test code like so:

    MyProject/src/main/java/com/acme/Widget.java
    MyProject/src/test/java/com/acme/WidgetTest.java
    

    (here, both src/main/java and src/test/java are source roots).

    Advantages:

    • Your tests have package (or "default") level access to your classes under test.
    • You can easily package only your production sources into a JAR by dropping src/test/java as a source root.

    One rule of thumb about class placement and packages:

    Generally speaking, well structured projects will be free of circular dependencies. Learn when they are bad (and when they are not), and consider a tool like JDepend or SonarJ that will help you eliminate them.

提交回复
热议问题