SpringBoot获取resources里配置文件中参数的3种方式

SpringBoot获取resources里配置文件里面配置的参数,有以下三种方式:

  1. 使用@Value注解获取配置文件中的值:
@Value("${key}")
private String value;
  1. 使用@PropertySource指定配置文件位置,并使用Environment获取其中的值:
@Configuration
@PropertySource("classpath:config.properties")
public class AppConfig {
@Autowired
private Environment env;

public void method() {
String value = env.getProperty("key");
}
}
  1. 使用@ConfigurationProperties注解绑定配置文件中的值到一个Java Bean上:
@Configuration
@ConfigurationProperties(prefix = "prefix")
public class ConfigProperties {
private String key;

public String getKey() {
return key;
}

public void setKey(String key) {
this.key = key;
}
}

//在调用的地方使用
@Autowired
private ConfigProperties configProperties;
String value = configProperties.getKey();
%title插图%num

相关文章 推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注