参考:SpringBoot第 1 讲:HelloWorld_秦毅翔的专栏-CSDN博客
二、修改pom.xml
pom.xml中只需要添加springboot依赖即可
三、读取SpringBoot的配置文件application.properties4.0.0 org.springframework.boot spring-boot-starter-parent1.5.2.RELEASE org.personal.qin.demos properties_read_demo1.0.0-SNAPSHOT jar UTF-8 UTF-8 1.8 org.springframework.boot spring-boot-starter-weborg.springframework spring-webmvc${project.artifactId} org.apache.maven.plugins maven-resources-pluginUTF-8 org.apache.maven.plugins maven-compiler-plugin1.8 1.8 UTF-8 org.springframework.boot spring-boot-maven-plugin
application.properties
server.port = 8080 server.context-path=/
ReadApplicationProperties.java
package demo.read.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties
public class ReadApplicationProperties {
@Value("${server.port}")
private String port;
public String read() {
return port;
}
}
四、读取普通properties文件
test.properties
test.demo.name = iPhone13 test.demo.num = 100 test.demo.price = 20.5
ReadNormalProperties.java
package demo.read.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Configuration
@PropertySource(value= {"test.properties"}, ignoreResourceNotFound = false)
public class ReadNormalProperties {
@Value("${test.demo.name}")
private String name;
@Value("${test.demo.num}")
private int num;
@Value("${test.demo.price}")
private double price;
public String read() {
String str = "读取字符串属性:"+name+"t";
str += "读取整型属性:"+num+"t";
str += "读取浮点型属性:"+price;
return str;
}
}
五、启动BootApplication并测试
package demo.read;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import demo.read.config.ReadApplicationProperties;
import demo.read.config.ReadNormalProperties;
@SpringBootApplication
@RestController
public class PropertiesBootApplication {
@Autowired
private ReadNormalProperties readProperties;
@Autowired
private ReadApplicationProperties readApplicationProperties;
@GetMapping("t1")
public String test1() {
return readProperties.read();
}
@GetMapping("t2")
public String test2() {
return readApplicationProperties.read();
}
public static void main(String[] args) {
SpringApplication.run(PropertiesBootApplication.class, args);
}
}
六、源代码
https://download.csdn.net/download/qzc70919700/30498626



