14. Structuring Your Code(组织您的代码)
1 | Spring Boot does not require any specific code layout to work. |
Spring Boot不需要任何特殊的代码框架就能运行。然而,有一些最佳实践可以给予您更多的帮助。
14.1 Using the “default” Package(使用默认包)
1 | When a class does not include a package declaration, it is |
当一个类不包含包声明时,它是被认为是在“默认包”中。 使用“默认包”通常是不鼓励的,应该是
避免。 它可能会导致Spring Boot的特殊问题,诸如在使用@ComponentScan,@EntityScan或@SpringBootApplicationannotations的应用程序,因为每个包里的每个类都会被读取。
1 | We recommend that you follow Java’s recommended package naming |
我们建议您遵循Java推荐的软件包命名约定并使用反向域名(例如,com.example.project)。
14.2 Locating the Main Application Class(定位主应用类)
1 | We generally recommend that you locate your main application |
我们通常推荐您将主应用类放到高于其他的类的根目录。@SpringBootApplication注解一般用于您的主应用类上,它隐含地为某些项目定义了一个基础“搜索包”。举个例子,如果你正在写一个JPA应用程序,@SpringBootApplication注释类所在的包将会用于搜索@Entity注解。 使用根包也允许组件扫描仅适用于您的项目。1
2
3
4If you don’t want to use @SpringBootApplication,
the @EnableAutoConfiguration and @ComponentScan
annotations that it imports defines that behaviour
so you can also use that instead.
如果您不想使用注解@SpringBootApplication,注解@EnableAutoConfiguration 和 @ComponentScan组合使用可以起到替代它的作用。1
The following listing shows a typical layout:
以下的列表显示了一个典型的类和包结构布局:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16com
+- example
+- myapplication
+- Application.java
|
+- customer
| +- Customer.java
| +- CustomerController.java
| +- CustomerService.java
| +- CustomerRepository.java
|
+- order
+- Order.java
+- OrderController.java
+- OrderService.java
+- OrderRepository.java
1 | The Application.java file would declare the main method, |
Application.java文件将定义main方法,已经基本的@SpringBootApplication如下:1
2
3
4
5
6
7
8
9
10
11
12
13package com.example.myapplication;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}