Java project structure explained for newbies?

前端 未结 10 944
攒了一身酷
攒了一身酷 2020-12-07 13:15

I come from a .NET background and am completely new to Java and am trying to get my head around the Java project structure.

My typical .NET solution structure conta

10条回答
  •  有刺的猬
    2020-12-07 13:48

    Here are some notes about Java packages that should get you started:

    The best practice with Java package names is to use the domain name of the organisation as the start of the package, but in reverse, e.g. if your company owns the domain "bobswidgets.com", you would start your package off with "com.bobswidgets".

    The next level down will often be the application or library level, so if it's your ecommerce libraries, it could be something like "com.bobswidgets.ecommerce".

    Further down than that often represents the architecture of your application. Classes and interfaces that are core to the project reside in the "root" e.g. com.bobswidgets.ecommerce.InvalidRequestException.

    Using packages to subdivide functionality further is common. usually the pattern is to put interfaces and exceptions into whatever the root of the subdivision is and the implementation into sub packages e.g.

    com.bobswidgets.ecommerce.payment.PaymentAuthoriser (interface)
    com.bobswidgets.ecommerce.payment.PaymentException
    com.bobswidgets.ecommerce.payment.paypal.PaypalPaymentAuthoriser (implementation)
    

    This makes it pretty easy to pull the "payment" classes and packages into their own project.

    Some other notes:

    Java packages are tightly coupled to directory structure. So, within a project, a class with a Package of com.example.MyClass will invariably be in com/example/MyClass.java. This is because when it is packaged up into a Jar, the class file will definitely be in com/example/MyClass.class.

    Java packages are loosely coupled to projects. It is quite common that projects will have their own distinct package names e.g. com.bobswidgets.ecommerce for ecommerce, com.bobswidgets.intranet for the intranet project.

    Jar files will container the class files that are the result of compiling your .java code into bytecodes. They are just zip files with .jar extension. The root of the Jar file is the root of the namespace hierarchy e.g. com.bobswidgets.ecommerce will be /com/bobswidgets/ecommerce/ in the Jar file. Jar files can also container resources e.g. property files etc.

提交回复
热议问题