Skip to content

Latest commit

 

History

History
84 lines (52 loc) · 3.43 KB

14.StructuringYourCode.md

File metadata and controls

84 lines (52 loc) · 3.43 KB

14. Structuring Your Code

14. 组织你的代码

Spring Boot does not require any specific code layout to work. However, there are some best practices that help.

Spring Boot不需要任何代码布局来工作。然而,有很多最佳实践可以提供帮助。

Using the "default" Package

使用“默认”包

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, @EntityScan, or @SpringBootApplication annotations, since every class from every jar is read.

当一个类没有包含任何包声明时,它将使用“默认的包”。通常不建议使用“默认包”。对于使用@ComponentScan, @EntityScan, or @SpringBootApplication注解情况,它可能会导致每个jar的类都会被读取的特殊的问题。

Tip
小提示

We recommend that you follow Java's recommended package naming conventions and use a reversed domain name (for example, com.example.project).

我们推荐你遵循Java推荐的包命名约定:使用一个反向域名(比如,com.example.project).

Location the Main Application Class

定位应用程序入口类

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 fo @Entity items. Using a root package also allows component scan to apply only on your project.

我们通常建议你将饮用程序入口类定位在其他类上方的根节点包中。@SpringBootApplication注解放在你的入口类中,它隐式地为某些项目定义了一个基本的“搜索包”。例如,如果你编写一个JAP应用时,则使用@SpringBootApplication注解类的包来搜索@Entity项目。使用根节点包也允许组建扫描适用于你的项目。

Tip
小提示

If you don't want to use @SpringBootApplication, the @EnableAutoConfiguration and @ComponentScan annotations that it imports defines that behaviour so you can also use that instaead.

如果你不想使用@SpringBootApplication,则可以导入@EnableAutoConfiguration@ComponentScan 注解定义该行为来代替它。

The following listing shows a typical layout:

下面展示了一个典型的布局:

com
+ - example
	+ - myapplication
	|
	+ - customer
	|	+ - Customer.java
	|	+ - CustomerController.java
	|	+ - CustomerService.java
	|	+ - CustomerRepository.java
	|
	+ - Order
	|	+ - Order.java
	|	+ - OrderController.java
	|	+ - OrderService.java
	|	+ - OrderRepository.java

The Application.java file would declare the main method, along with the basic @SpringBootApplication, as follows:

Application.java文件中声明了入口函数和基本的@SpringBootApplication,如下所示:

package com.example.myapplication;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}
}