1. 在src/main/resources下, 新建application.properties
1.1. 修改内嵌容器的端口号

1.2. 配置随机值

1.3. 变量引用

1.4. 自定义属性配置

2. 全局属性配置文件例子
2.1. 使用maven构建SpringBoot的名叫spring-boot-applicationproperties-variable项目

2.2. 配置pom.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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.bjbs</groupId>
<artifactId>spring-boot-applicationproperties-variable</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.13.RELEASE</version>
</parent>
<!-- 修改jdk版本 -->
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- springBoot的启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>
2.3. 在src/main/resources下, 新建application.properties
server.port=8888
num=${random.int[1024,9999]}
msg=Hello World ${num}
2.4. 新建ConfigController.java
package com.bjbs.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ConfigController {
@Value("${msg}")
private String msg;
@RequestMapping("/showMsg")
public String showMsg() {
return msg;
}
}
2.5. 新建App.java
package com.bjbs;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* spring Boot启动器
*/
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
2.6. 运行项目

本文介绍了如何在SpringBoot中创建并配置`application.properties`文件,包括修改内嵌容器端口号、设置随机值、变量引用及自定义属性。通过一个实例展示了从创建maven项目到编写`ConfigController`,展示`msg`变量的注入,并运行项目。
1173

被折叠的 条评论
为什么被折叠?



