SpringBoot读取配置的6种方式
SpringBoot读取配置文件的方式主要有以下6种:
- 使用
@Value
注解 - 使用
Environment
类 - 使用
ConfigurationProperties
注解绑定一个类 - 使用
@PropertySource
加载指定配置文件 - 使用
@ConfigurationProperties
指定前缀加载配置文件 - 使用
RandomValuePropertySource
读取随机值
以下是每种方式的示例代码:
- 使用
@Value
注解
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class MyBean {
@Value("${my.property}")
private String myProperty;
// getter and setter
}
- 使用
Environment
类
import org.springframework.core.env.Environment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class MyBean {
private final Environment env;
@Autowired
public MyBean(Environment env) {
this.env = env;
}
public String getMyProperty() {
return env.getProperty("my.property");
}
}
- 使用
ConfigurationProperties
注解绑定一个类
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "my")
public class MyProperties {
private String property;
// getter and setter
}
- 使用
@PropertySource
加载指定配置文件
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Configuration
@PropertySource("classpath:myconfig.properties")
public class MyConfiguration {
// ...
}
- 使用
@ConfigurationProperties
指定前缀加载配置文件
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "my")
public class MyConfig {
private String property;
// getter and setter
}
- 使用
RandomValuePropertySource
读取随机值
import org.springframework.beans.factory.config.RandomValuePropertySource;
public class MyRandomValue {
private String randomValue;
public MyRandomValue(String randomValue) {
this.randomValue = randomValue;
}
// getter and setter
}
在SpringBoot应用中,通常推荐使用@ConfigurationProperties
和Environment
类来读取配置,因为它们支持配置的校验、数据绑定和松散耦合的配置管理。
评论已关闭