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

后端 未结 10 1440
轻奢々
轻奢々 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 05:54

    Where I'm working, we're using Maven 2 and we have a pretty nice archetype for our projects. The goal was to obtain a good separation of concerns, thus we defined a project structure using multiple modules (one for each application 'layer'): - common: common code used by the other layers (e.g., i18n) - entities: the domain entities - repositories: this module contains the daos interfaces and implementations - services-intf: interfaces for the services (e.g, UserService, ...) - services-impl: implementations of the services (e.g, UserServiceImpl) - web: everything regarding the web content (e.g., css, jsps, jsf pages, ...) - ws: web services

    Each module has its own dependencies (e.g., repositories could have jpa) and some are project wide (thus they belong in the common module). Dependencies between the different project modules clearly separate things (e.g., the web layer depends on the service layer but doesn't know about the repository layer).

    Each module has its own base package, for example if the application package is "com.foo.bar", then we have:

    com.foo.bar.common
    com.foo.bar.entities
    com.foo.bar.repositories
    com.foo.bar.services
    com.foo.bar.services.impl
    ...
    

    Each module respects the standard maven project structure:

       src\
       ..main\java
         ...\resources
       ..test\java
         ...\resources
    

    Unit tests for a given layer easily find their place under \src\test... Everything that is domain specific has it's place in the entities module. Now something like a FileStorageStrategy should go into the repositories module, since we don't need to know exactly what the implementation is. In the services layer, we only know the repository interface, we do not care what the specific implementation is (separation of concerns).

    There are multiple advantages to this approach:

    • clear separation of concerns
    • each module is packageable as a jar (or a war in the case of the web module) and thus allows for easier code reuse (e.g., we could install the module in the maven repository and reuse it in another project)
    • maximum independence of each part of the project

    I know this doesn't answer all your questions, but I think this could put you on the right path and could prove useful to others.

提交回复
热议问题