spring_reference/III. Using Spring Boot/14.2. Locating the main app...

44 lines
1.5 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

### 14.2. 定位main应用类
我们通常建议你将main应用类放在位于其他类上面的根包root package中。通常使用`@EnableAutoConfiguration`注解你的main类并且暗地里为某些项定义了一个基础“search package”。例如如果你正在编写一个JPA应用被`@EnableAutoConfiguration`注解的类所在包将被用来搜索`@Entity`项。
使用根包允许你使用`@ComponentScan`注解而不需要定义一个`basePackage`属性。如果main类位于根包中你也可以使用`@SpringBootApplication`注解。
下面是一个典型的结构:
```shell
com
+- example
+- myproject
+- Application.java
|
+- domain
| +- Customer.java
| +- CustomerRepository.java
|
+- service
| +- CustomerService.java
|
+- web
+- CustomerController.java
```
`Application.java`文件将声明`main`方法,还有基本的`@Configuration`。
```java
package com.example.myproject;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```