- 前置介绍
- 读取一般变量 ValueController
- 读取静态变量 ValueController
总结一下SpringBoot项目中一般用到的@Value注解(来自由org.springframework.beans.factory.annotation.Value)
读取配置文件的使用
-
目录结构
-
依赖
org.springframework.boot spring-boot-starter-web 2.3.12.RELEASE
- 配置文件
server.port=8080 test.url=https://editor.csdn.net读取一般变量 ValueController
package com.value;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ValueController {
@Value("${test.url}")
private String url;
@GetMapping("test")
public void test() {
System.out.println("url = " + url);
}
}
访问localhost:8080/test,成功读取到参数
读取静态变量 ValueControllerpackage com.value;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Component
public class ValueController {
private static String url;
@Value("${test.url}")
public void setUrl(String url) {
this.url = url;
}
@GetMapping("test")
public void test() {
System.out.println("url = " + url);
}
}
访问localhost:8080/test,成功读取到参数



