本文演示從零構建一個基於 Spring Boot 1.4.2 的 Web 應用,集成 Undertow 容器、Velocity 模板引擎,並產出可執行 Fat JAR。
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.2.RELEASE</version>
</parent>
<dependencies>
<!-- Web 起步依賴,排除 Tomcat,引入 Undertow -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
</dependency>
<!-- Velocity 模板 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-velocity</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
@SpringBootApplication // = @Configuration + @EnableAutoConfiguration + @ComponentScan
@EnableTransactionManagement // 啟用註解事務
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@Configuration:標識配置類,相當於 XML <beans>。@EnableAutoConfiguration:根據 classpath 自動裝配 (見 spring.factories)。@ComponentScan:掃描同包及子包下的 @Component/@Service/@Repository/@Controller。server:
port: 8081
context-path: /test
logging:
config: classpath:logback.xml
level:
org.springframework.web: DEBUG
spring:
velocity:
charset: UTF-8
properties:
input.encoding: UTF-8
output.encoding: UTF-8
toolbox-config-location: /templates/toolbox.xml
src/main/resources
├── templates/ # Velocity 模板 (*.vm)
│ ├── index.vm
│ └── toolbox.xml
└── static/ # 靜態資源 (css/js/images)
└── ...
@Controller
public class IndexController {
@GetMapping("/")
public String index(Model model) {
model.addAttribute("msg", "Hello, Spring Boot + Velocity!");
return "index"; // 對應 templates/index.vm
}
}
mvn clean package java -jar target/your-app.jar # 或 IDE 直接運行 Application.main()
啟動日誌顯示 Undertow 啟動端口 8081,上下文路徑 /test。
瀏覽器訪問 https://localhost:8081/test/,顯示模板渲染結果。
| 優點 | 缺點 |
|---|---|
| 零 XML、啟動器依賴傳遞、內嵌容器打包單 JAR、配置外部化、Actuator 監控 | 自動配置「黑盒」排查難、版本升級破壞性變更大、對 Spring 核心原理不了解者易踩坑 |

下一篇將介紹 Spring Boot 整合 MyBatis 實戰。