Spring Boot 环境变量读取 和 属性对象的绑定
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
@ConfigurationProperties(prefix = "myapp")
public MyAppProperties myAppProperties() {
return new MyAppProperties();
}
}
@ConfigurationProperties(prefix = "myapp")
class MyAppProperties {
private String name;
private int version;
// standard getters and setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
}
在这个简化的代码示例中,我们定义了一个Spring Boot应用程序的入口点,并通过@Bean
注解和@ConfigurationProperties
注解将一个属性对象绑定到Spring的上下文中。MyAppProperties
类包含了应用程序特有的配置属性,它们可以通过application.properties
或application.yml
文件进行配置。这种方式使得配置管理变得更加集中和易于维护。
评论已关闭