获取整个SpringBoot环境中指定属性对应的值
获取整个SpringBoot环境中指定属性对应的值
方式一,使用System.getProperty(p)
这种方式返回值为String类型,获取不到SpringBoot配置文件的环境变量,只能获取Java系统环境变量的值
方式二,使用System.getEnv(p)
这种方式返回值为Object类型,同方式一,获取不到SpringBoot配置文件的环境变量,只能获取Java系统环境变量的值
方式三,applicationContext.getEnvironment().getProperty(p)
这种方式返回值为String类型,能获得SpringBoot配置文件的值,也能获取系统本身的环境变量的值
代码如下
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
@RestController
@RequestMapping("/test")
public class TestController implements ApplicationContextAware {
//@Autowired
//private FileService fileService;
private ApplicationContext applicationContext;
//@Resource
//private Environment environment;
@RequestMapping("/env")
public Object getEnv(String p) throws IOException {
if (p == null) {
p = "server.port";
}
String property = System.getProperty(p);
System.out.println("property = " + property);
return p + " = " + property;
}
@RequestMapping("/env1")
public Object getEnv1(String p) throws IOException {
if (p == null) {
p = "server.port";
}
String property = applicationContext.getEnvironment().getProperty(p);
return p + " = " + property;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
测试结果
其他方式
- 注解
@Value,作用在字段上
@Value("${server.port:8080}")
private String port;
- 注解
@ConfigurationProperties,作用在类上
@ConfigurationProperties("server")
public class PortProperties {
private Integer port;
}


浙公网安备 33010602011771号