Products
GG网络技术分享 2025-11-12 23:12 4
Spring Boot 自定义配置文件的用方法如下:
YAML 是一种直观的数据序列化格式,容易于阅读和编写。在 Spring Boot 中,YAML 文件通常以 .yml 或 .yaml 为
名。

application.yml 示例:
yaml
server:
port: 8080
spring:
datasource:
url: jdbc:mysql://localhost/test
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
Properties 文件以 .properties 为
名,它用键值对来存储配置信息。
application.properties 示例:
properties
server.port=8080
spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
Spring Boot 的 Environment 对象给了获取和设置周围变量的Neng力。
示例:
java import org.springframework.core.env.Environment;
@SpringBootApplication public class MyApplication implements CommandLineRunner {
private final Environment env;
public MyApplication {
this.env = env;
}
@Override
public void run throws Exception {
System.out.println);
System.out.println);
}
public static void main {
SpringApplication.run;
}
}
通过命令行参数传递配置信息。
shell
java -jar myProject.jar --spring.datasource.url=jdbc:mysql://localhost/test
在 Java 代码中获取:
java
@Override
public void run throws Exception {
for {
if ) {
System.out.println + 1));
}
}
}
用周围变量来设置配置信息。
shell
export MY_DB_URL=jdbc:mysql://localhost/test
java -jar myProject.jar
java
@Override
public void run throws Exception {
System.out.println);
}
用这些个方法, 开发者Neng根据需要灵活地配置 Spring Boot 应用程序,而无需沉新鲜编译代码。
Demand feedback