总结一下SpringBoot项目中一般用到的@Value注解(org.springframework.beans.factory.annotation.Value)
前置介绍
目录结构
依赖 pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.3.12.RELEASE</version>
</dependency>
</dependencies>
配置文件 application.properties
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,成功读取到参数
读取静态变量 ValueController
package 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,成功读取到参数