Structuring Your Code
Spring Boot 不要求任何特定的代码布局才能工作。但是,有一些有助于解决此问题的最佳实践。
Spring Boot does not require any specific code layout to work. However, there are some best practices that help.
如果你希望强制执行基于域名的结构,请查看 Spring Modulith。 |
If you wish to enforce a structure based on domains, take a look at Spring Modulith. |
Using the “default” Package
当一个类不包含 package
声明时,它被认为是在 “default package” 中。通常不鼓励使用 “default package”,并且应该避免使用它。它可能给使用 @ComponentScan
、@ConfigurationPropertiesScan
、@EntityScan
或 @SpringBootApplication
注解的 Spring Boot 应用程序带来特殊问题,因为会读取每个 jar 中的每个类。
When a class does not include a package
declaration, it is considered to be in the “default package”.
The use of the “default package” is generally discouraged and should be avoided.
It can cause particular problems for Spring Boot applications that use the @ComponentScan
, @ConfigurationPropertiesScan
, @EntityScan
, or @SpringBootApplication
annotations, since every class from every jar is read.
我们建议您遵循 Java 建议的软件包命名约定,并使用反向域名(例如 |
We recommend that you follow Java’s recommended package naming conventions and use a reversed domain name (for example, |
Locating the Main Application Class
我们通常建议您将主应用程序类置于其他类之上的根软件包中,@SpringBootApplication
annotation通常置于您的主类上,它隐式地定义了特定项目的基"`search package`"。例如,如果您编写 JPA 应用程序,带`@SpringBootApplication`注释的类的软件包将用于搜索`@Entity` 项目。使用根软件包还允许组件扫描仅应用于您的项目。
We generally recommend that you locate your main application class in a root package above other classes.
The @SpringBootApplication
annotation is often placed on your main class, and it implicitly defines a base “search package” for certain items.
For example, if you are writing a JPA application, the package of the @SpringBootApplication
annotated class is used to search for @Entity
items.
Using a root package also allows component scan to apply only on your project.
如果您不想使用`@SpringBootApplication`,它导入的`@EnableAutoConfiguration` 和 `@ComponentScan`注释定义了该行为,所以您也可以使用它们代替。 |
If you do not want to use |
以下列表显示了典型布局:
The following listing shows a typical layout:
com
+- example
+- myapplication
+- MyApplication.java
|
+- customer
| +- Customer.java
| +- CustomerController.java
| +- CustomerService.java
| +- CustomerRepository.java
|
+- order
+- Order.java
+- OrderController.java
+- OrderService.java
+- OrderRepository.java
MyApplication.java`文件将声明`main
方法,以及基本`@SpringBootApplication`,如下所示:
The MyApplication.java
file would declare the main
method, along with the basic @SpringBootApplication
, as follows: