Spring Boot项目配置与运行示例
以下是一个基于 Maven 的 Spring Boot 项目的配置和运行介绍,结合了多环境构建参数的使用,并展示了如何打包成可运行的 JAR 文件。
1. 项目结构
一个典型的 Spring Boot 项目结构如下:
springboot-multi-environment
├── src
│ ├── main
│ │ ├── java
│ │ │ └── com.example.demo
│ │ │ └── DemoApplication.java
│ │ └── resources
│ │ ├── application.properties
│ │ ├── dev.properties
│ │ └── prod.properties
├── pom.xml
2. pom.xml 配置
xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>springboot-multi-environment</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
3. 资源文件配置
3.1 application.properties
properties
spring.datasource.url=${db.url}
spring.datasource.username=${db.username}
spring.datasource.password=${db.password}
3.2 dev.properties
properties
db.url=jdbc:mysql://localhost:3306/dev_db
db.username=dev_user
db.password=dev_password
3.3 prod.properties
properties
db.url=jdbc:mysql://prod.example.com:3306/prod_db
db.username=prod_user
db.password=prod_password
4. 启动类 DemoApplication.java
java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
5. 打包与运行
5.1 打包为可运行 JAR
执行以下命令将项目打包为可运行的 JAR 文件:
bash
mvn clean package
生成的 JAR 文件位于 target 目录下,例如:springboot-multi-environment-1.0-SNAPSHOT.jar。
5.2 运行 JAR 文件
bash
java -jar springboot-multi-environment-1.0-SNAPSHOT.jar
5.3 指定环境
在运行时指定环境参数,例如使用开发环境:
bash
java -Denv=dev -jar springboot-multi-environment-1.0-SNAPSHOT.jar
或者使用生产环境:
bash
java -Denv=prod -jar springboot-multi-environment-1.0-SNAPSHOT.jar
6. 项目说明
- Spring Boot:简化了 Spring 应用的初始搭建和开发。
- Maven:用于项目依赖管理、构建和打包。
- 多环境支持:通过资源过滤功能,实现不同环境的配置切换。
- 可运行 JAR :使用
spring-boot-maven-plugin插件将项目打包为可直接运行的 JAR 文件。
以上是一个完整的 Spring Boot 项目配置和运行示例,适用于实际开发中的多环境部署需求。