SpringBoot 获取配置文件值、获取环境变量的方式
文章目录
- 1. 配置文件基础
- 2. 使用 @Value 注解获取配置值
- 2.1 基本用法
- 2.2 配置示例 (application.yml)
- 3. 使用 @ConfigurationProperties 批量注入
- 3.1 创建配置类
- 3.2 启用配置属性
- 4. 使用 Environment 接口
- 5. 获取环境变量
- 5.1 直接获取系统环境变量
- 5.2 通过 Environment 获取环境变量
- 6. 配置文件的 Profile 支持
- 6.1 不同环境的配置文件
- 6.2 使用 Profile 的配置类
- 7. 高级用法:条件化配置
- 7.1 使用 @ConditionalOnProperty
- 8. 配置验证
- 8.1 添加验证注解
- 9. 实际应用示例
- 9.1 完整的服务类
- 10. 最佳实践建议
- 10.1 配置命名规范
- 10.2 安全敏感配置
- 11. 配置刷新机制
- 12、环境变量
- 程序启动时的命令行参数
- 程序启动时的应用环境变量
- 总结
1. 配置文件基础
Spring Boot 支持多种格式的配置文件:
application.propertiesapplication.ymlapplication.yaml
配置文件默认加载顺序:
file:./config/(项目根目录下的config子目录)file:./(项目根目录)classpath:/config/(resources/config目录)classpath:/(resources目录)
2. 使用 @Value 注解获取配置值
2.1 基本用法
@ComponentpublicclassConfigService{// 获取普通配置值@Value("${app.name}")privateStringappName;// 设置默认值@Value("${server.port:8080}")privateintport=8080;// 获取布尔值@Value("${app.enabled:true}")privatebooleanenabled;// 获取列表值@Value("${app.tags:java,spring}")privateList<String>tags;// 获取数组值@Value("${app.servers}")privateString[]servers;publicvoidprintConfig(){System.out.println("App Name: "+appName);System.out.println("Port: "+port);System.out.println("Enabled: "+enabled);System.out.println("Tags: "+Arrays.toString(tags.toArray()));System.out.println("Servers: "+Arrays.toString(servers));}}2.2 配置示例 (application.yml)
app:name:MySpringBootApplicationenabled:truetags:java,spring,bootservers:-server1-server2-server3server:port:80803. 使用 @ConfigurationProperties 批量注入
3.1 创建配置类
@ConfigurationProperties(prefix="app")@ComponentpublicclassAppProperties{privateStringname;privatebooleanenabled;privateStringversion;privateDatabasedatabase;privateList<String>features;privateMap<String,String>properties;// 内部类定义嵌套配置publicstaticclassDatabase{privateStringurl;privateStringusername;privateStringpassword;privateintmaxConnections;// getter 和 setter 方法publicStringgetUrl(){returnurl;}publicvoidsetUrl(Stringurl){this.url=url;}publicStringgetUsername(){returnusername;}publicvoidsetUsername(Stringusername){this.username=username;}publicStringgetPassword(){returnpassword;}publicvoidsetPassword(Stringpassword){this.password=password;}publicintgetMaxConnections(){returnmaxConnections;}publicvoidsetMaxConnections(intmaxConnections){this.maxConnections=maxConnections;}}// getter 和 setter 方法publicStringgetName(){returnname;}publicvoidsetName(Stringname){this.name=name;}publicbooleanisEnabled(){returnenabled;}publicvoidsetEnabled(booleanenabled){this.enabled=enabled;}publicStringgetVersion(){returnversion;}publicvoidsetVersion(Stringversion){this.version=version;}publicDatabasegetDatabase(){returndatabase;}publicvoidsetDatabase(Databasedatabase){this.database=database;}publicList<String>getFeatures(){returnfeatures;}publicvoidsetFeatures(List<String>features){this.features=features;}publicMap<String,String>getProperties(){returnproperties;}publicvoidsetProperties(Map<String,String>properties){this.properties=properties;}}3.2 启用配置属性
在主类或配置类上添加注解:
@SpringBootApplication@EnableConfigurationProperties(AppProperties.class)publicclassApplication{publicstaticvoidmain(String[]args){SpringApplication.run(Application.class,args);}}或者在application.yml中配置:
app:name:MyApplicationenabled:trueversion:1.0.0features:-feature1-feature2-feature3properties:key1:value1key2:value2database:url:jdbc:mysql://localhost:3306/mydbusername:rootpassword:passwordmax-connections:1004. 使用 Environment 接口
@ServicepublicclassEnvironmentService{@AutowiredprivateEnvironmentenvironment;publicvoidgetEnvironmentValues(){// 获取配置值StringappName=environment.getProperty("app.name");Stringport=environment.getProperty("server.port");StringdefaultPort=environment.getProperty("server.port","8080");// 获取特定类型的值IntegerserverPort=environment.getProperty("server.port",Integer.class,8080);BooleandebugMode=environment.getProperty("debug",Boolean.class,false);// 检查属性是否存在if(environment.containsProperty("app.name")){System.out.println("App name exists: "+appName);}// 获取所有活跃的配置文件String[]activeProfiles=environment.getActiveProfiles();String[]defaultProfiles=environment.getDefaultProfiles();System.out.println("Active profiles: "+Arrays.toString(activeProfiles));System.out.println("Default profiles: "+Arrays.toString(defaultProfiles));}}5. 获取环境变量
5.1 直接获取系统环境变量
@ComponentpublicclassSystemEnvService{publicvoidgetSystemEnvironment(){// 方式1:通过 System.getenv()StringhomeDir=System.getenv("HOME");Stringpath=System.getenv("PATH");StringuserName=System.getenv("USER");// 方式2:通过 Environment 接口Environmentenv=newStandardEnvironment();StringhomeFromEnv=env.getProperty("HOME");// 方式3:通过 @Value 注解@Value("${HOME:#{null}}")// 注意:环境变量通常不以 $ 开头privateStringhomePath;System.out.println("Home directory: "+homeDir);System.out.println("PATH: "+path);System.out.println("User: "+userName);}}5.2 通过 Environment 获取环境变量
@ServicepublicclassEnvVariableService{@AutowiredprivateEnvironmentenvironment;publicvoidgetEnvironmentVariables(){// 获取环境变量(注意:环境变量名通常大写)StringdbHost=environment.getProperty("DB_HOST");StringdbPort=environment.getProperty("DB_PORT");StringsecretKey=environment.getProperty("SECRET_KEY");// 设置默认值StringdbHostWithDefault=environment.getProperty("DB_HOST","localhost");System.out.println("DB Host: "+dbHost);System.out.println("DB Port: "+dbPort);System.out.println("Secret Key: "+secretKey);}}6. 配置文件的 Profile 支持
6.1 不同环境的配置文件
application.yml(默认配置)application-dev.yml(开发环境)application-test.yml(测试环境)application-prod.yml(生产环境)
6.2 使用 Profile 的配置类
@Configuration@Profile("dev")publicclassDevConfig{@BeanpublicStringdevDatabaseUrl(){return"jdbc:h2:mem:devdb";}}@Configuration@Profile("!dev")// 非开发环境publicclassProdConfig{@BeanpublicStringprodDatabaseUrl(){return"jdbc:mysql://prod-server:3306/proddb";}}7. 高级用法:条件化配置
7.1 使用 @ConditionalOnProperty
@ConfigurationpublicclassConditionalConfig{@Bean@ConditionalOnProperty(name="app.feature.enabled",havingValue="true",matchIfMissing=false)publicFeatureServicefeatureService(){returnnewFeatureServiceImpl();}@Bean@ConditionalOnProperty(name="app.cache.type",havingValue="redis",matchIfMissing=false)publicCacheServiceredisCacheService(){returnnewRedisCacheService();}@Bean@ConditionalOnProperty(name="app.cache.type",havingValue="memory",matchIfMissing=true)publicCacheServicememoryCacheService(){returnnewMemoryCacheService();}}8. 配置验证
8.1 添加验证注解
@ConfigurationProperties(prefix="app")@Component@ValidatedpublicclassValidatedAppProperties{@NotBlank(message="应用名称不能为空")privateStringname;@Min(value=1,message="端口号必须大于0")@Max(value=65535,message="端口号不能超过65535")privateintport;@Pattern(regexp="^\\d+\\.\\d+\\.\\d+$",message="版本号格式不正确,应为 x.y.z 格式")privateStringversion;@AssertTrue(message="应用必须启用才能正常工作")privatebooleanenabled;// getter 和 setter 方法...}9. 实际应用示例
9.1 完整的服务类
@Service@Slf4jpublicclassConfigurationManager{@Value("${app.name:DefaultApp}")privateStringappName;@Value("${app.version:1.0.0}")privateStringappVersion;@AutowiredprivateEnvironmentenvironment;@AutowiredprivateAppPropertiesappProperties;publicvoiddisplayAllConfigs(){log.info("=== 应用配置信息 ===");log.info("App Name: {}",appName);log.info("App Version: {}",appVersion);log.info("=== 通过 Environment 获取 ===");log.info("Server Port: {}",environment.getProperty("server.port"));log.info("Active Profiles: {}",Arrays.toString(environment.getActiveProfiles()));log.info("=== 通过 @ConfigurationProperties 获取 ===");log.info("App Properties Name: {}",appProperties.getName());log.info("App Properties Enabled: {}",appProperties.isEnabled());log.info("Database URL: {}",appProperties.getDatabase().getUrl());log.info("=== 环境变量示例 ===");log.info("JAVA_HOME: {}",System.getenv("JAVA_HOME"));log.info("OS: {}",System.getProperty("os.name"));}publicStringgetProperty(Stringkey){returnenvironment.getProperty(key);}publicStringgetProperty(Stringkey,StringdefaultValue){returnenvironment.getProperty(key,defaultValue);}public<T>TgetProperty(Stringkey,Class<T>targetType,TdefaultValue){returnenvironment.getProperty(key,targetType,defaultValue);}}10. 最佳实践建议
10.1 配置命名规范
# 推荐的命名方式my-app:service:timeout:30sretry-count:3database:connection-timeout:20spool-size:10# 避免驼峰命名(虽然也支持)myAppServiceTimeout:30s10.2 安全敏感配置
// 对于密码等敏感信息,建议使用配置解密@ConfigurationProperties(prefix="app.security")@ComponentpublicclassSecurityProperties{privateStringencryptedPassword;// 不直接暴露密码字段,而是提供解密方法publicStringgetDecryptedPassword(){// 实现解密逻辑returndecrypt(encryptedPassword);}privateStringdecrypt(StringencryptedValue){// 解密实现returnencryptedValue;// 简化示例}}11. 配置刷新机制
对于需要动态刷新的配置,可以结合 Spring Cloud Config 或使用@RefreshScope:
@RestController@RefreshScopepublicclassConfigController{@Value("${app.message:Hello Default}")privateStringmessage;@GetMapping("/message")publicStringgetMessage(){returnmessage;}}12、环境变量
程序启动时的命令行参数
- java设置方式
java-jarapp.jar--jasypt.encryptor.password=saltIDEA设置方式
读取方式
System.getenv(jasypt.encryptor.password);程序启动时的应用环境变量
- java启动设置方式
java-jarapp.jar-Djasypt.encryptor.password=saltIDEA设置方式
读取方式
System.getProperty(jasypt.encryptor.password);总结
Spring Boot 提供了多种灵活的方式来获取配置值和环境变量:
- @Value: 适用于简单的单个值注入
- @ConfigurationProperties: 适用于复杂对象的批量配置
- Environment: 适用于程序化访问配置值
- Profile: 适用于不同环境的差异化配置
- 条件化配置: 适用于基于条件的配置加载
