承接上一節 Spring Boot 入門程序,本文將深入介紹官方推薦的標準開發模式,並構建包含 Controller、Service、Domain 層的完整應用結構,展示配置屬性綁定、依賴注入等核心機制的實際應用。
遵循官方建議,將主啟動類置於根包路徑(如 com.xxx.firstboot)下,以便 @ComponentScan 自動掃描子包。典型分層結構如下:
@ConfigurationProperties 實現配置自動綁定@Service 標識,注入 Domain 對象@RestController 暴露 RESTful API
採用 spring-boot-starter-parent 作為父項目,統一管理依賴版本;引入 spring-boot-starter-web 提供 Web 開發所需的 Spring MVC、Tomcat、Jackson 等組件;配置 spring-boot-maven-plugin 支援打包為可執行 JAR。
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.5.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
注意:若無法繼承官方父項目,可改用 dependencyManagement 導入 spring-boot-dependencies,並手動配置打包插件。
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@SpringBootApplication 組合了三大核心註解:
@Configuration:標識配置類,由 Spring 容器管理@EnableAutoConfiguration:啟用自動配置機制,根據類路徑依賴自動裝配 Bean@ComponentScan:掃描主類所在包及其子包(主類置於根包的關鍵原因)每個獨立 JAR(微服務)僅允許存在一個 main 方法作為啟動入口。
application.properties 是 Spring Boot 默認配置文件,集中管理數據源、HTTP 客戶端等各類配置:
user.id=1
user.username=zhaojigang
user.password=123
在 Domain 類上使用 @Component + @ConfigurationProperties(prefix="user") 即可實現屬性自動注入:
@Component
@ConfigurationProperties(prefix="user")
public class User {
private int id;
private String username;
private String password;
// getter/setter 省略
}
此方式比逐個使用 @Value("${user.id}") 更優雅;若同時存在 @ConfigurationProperties,則 @Value 失效。
UserService 注入 User 實體,提供業務方法:
@Service
public class UserService {
@Autowired
private User user;
public User getUser() { return user; }
}
UserController 使用 @RestController(等同於 @Controller + @ResponseBody)直接返回 JSON:
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/getUser")
public User getUser() {
return userService.getUser();
}
}
此即為 Spring Boot 開發中最基礎、最常用的標準模式(微服務多模塊結構後續介紹)。
@ConfigurationProperties / @ValueEnvironment 通過 getProperty() 獲取FileUtil 方式(不推薦)Spring Boot 提供大量開箱即用的 Starter,按需引入:
spring-boot-starter-webspring-boot-starter-data-jpa、spring-boot-starter-jdbcspring-boot-starter-securityspring-boot-starter-thymeleaf、spring-boot-starter-freemarkerspring-boot-starter-amqp、spring-boot-starter-activemqspring-boot-starter-actuator

提示:當前版本暫無官方 MyBatis Starter,需手動整合或使用第三方 Starter。