# 6.2. 构建你的代码

Spring Boot 不需要任何特定的代码布局即可工作。不过，有一些最佳实践可以提供帮助。

> 如果您希望强制执行基于域的结构，请查看[Spring Modulith](https://spring.io/projects/spring-modulith#overview)。

**6.2.1. 使用“默认”包**

当一个类不包含`package`声明时，它被认为位于“默认包”中。通常不鼓励并且应该避免使用“默认包”。对于使用`@ComponentScan`、`@ConfigurationPropertiesScan`、`@EntityScan`或`@SpringBootApplication`注释的 Spring Boot 应用程序，它可能会导致特定问题，因为每个 jar 中的每个类都会被读取。

> 我们建议您遵循 Java 推荐的包命名约定并使用反向域名（例如`com.example.project`）。

**6.2.2. 找到主应用程序类**

我们通常建议您将主应用程序类放在根包中其他类之上。该[`@SpringBootApplication`注释](https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#using.using-the-springbootapplication-annotation)通常放置在您的主类上，它隐式地定义了某些项目的基本“搜索包”。例如，如果您正在编写 JPA 应用程序，则使用带`@SpringBootApplication`注释的类的包来搜索`@Entity`项目。使用根包还允许组件扫描仅应用于您的项目。

如果您不想使用`@SpringBootApplication`，它导入的 `@EnableAutoConfiguration`和`@ComponentScan`注释定义了该行为，因此您也可以使用它们。

以下清单显示了典型的布局：

```
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`，如下所示：

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


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://doc.shiker.tech/spring-boot-can-kao-wen-dang/6.-shi-yong-spring-boot-jin-xing-kai-fa/6.2.-gou-jian-ni-de-dai-ma.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
