当前位置: 首页 > news >正文

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.properties
  • application.yml
  • application.yaml

配置文件默认加载顺序:

  1. file:./config/(项目根目录下的config子目录)
  2. file:./(项目根目录)
  3. classpath:/config/(resources/config目录)
  4. 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:8080

3. 使用 @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:100

4. 使用 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:30s

10.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=salt
  • IDEA设置方式

  • 读取方式

System.getenv(jasypt.encryptor.password);

程序启动时的应用环境变量

  • java启动设置方式
java-jarapp.jar-Djasypt.encryptor.password=salt
  • IDEA设置方式

  • 读取方式

System.getProperty(jasypt.encryptor.password);

总结

Spring Boot 提供了多种灵活的方式来获取配置值和环境变量:

  1. @Value: 适用于简单的单个值注入
  2. @ConfigurationProperties: 适用于复杂对象的批量配置
  3. Environment: 适用于程序化访问配置值
  4. Profile: 适用于不同环境的差异化配置
  5. 条件化配置: 适用于基于条件的配置加载
http://www.jsqmd.com/news/721310/

相关文章:

  • 别再只会用jstack了!用Arthas的thread和dashboard命令5分钟定位线上CPU飙升问题
  • 5分钟掌握暗黑2存档编辑器:打造完美角色的终极指南
  • microeco:让微生物组数据分析变得简单高效的终极解决方案
  • AI降本工具哪个好?率零10万字套餐宿舍拼单分摊预算紧首选! - 我要发一区
  • 终极指南:如何在3分钟内用gh-dash实现PR精准筛选,从杂乱信息到高效看板的革命性转变
  • Phi-3.5-mini-instruct助力Python爬虫开发:智能解析与反反爬策略生成
  • 终极Cypress存储测试指南:轻松掌握localStorage和sessionStorage全方位测试
  • dateparse测试驱动开发:编写健壮的日期解析代码
  • Pixelle-Video深度评测:全自动AI短视频引擎的技术架构与多模态生成能力分析
  • 小鹏校招 C++ 考试题到底怎么考?它不是互联网后端题,是车企里的系统工程题
  • 突破限制:Cursor Free VIP如何重塑AI编程体验的技术演进
  • 商汤校招 C++ 考试题到底怎么考?这篇只能写题型线索,不能硬装完整真题
  • RSSHub Radar:智能浏览器扩展,一键发现并订阅全网RSS内容
  • 如何快速上手 Next.js App Router:10个必学的新特性解析
  • 突破性能瓶颈:Leptos企业级应用架构设计终极指南
  • 【PHP 8.9 GC革命性突破】:内存泄漏率下降73%、循环引用回收提速4.8倍,你还在用PHP 8.1的旧回收器?
  • QMCDecode:3步解决QQ音乐加密格式的跨平台播放难题
  • LeetCode HOT100 - 二叉树展开为链表
  • 4月30日多因子共振节点:鲍威尔“收官效应”与权力结构重塑的预期重构
  • 3步实现视频流畅度飞跃:Flowframes AI插帧实战指南
  • Geatpy旅行商问题(TSP)求解:编码策略与优化技巧
  • NowinAndroid插件化模块设计终极指南:从零到一构建现代化Android应用架构
  • Netflix克隆项目测试策略:Jest与React Testing Library最佳实践
  • 黄金首饰价格查询系统源码_已对接数据接口 贵金属价格查询API源码
  • 【自用】OpenCode基本使用以及使用过程中遇到的问题
  • lvgl基础
  • python basedpyright
  • 别再只会addItem了!PyQt5 QComboBox的增删改查与事件绑定保姆级教程
  • AI降本工具哪个好?多平台需求选嘎嘎降AI一份订单管9平台! - 我要发一区
  • 深度解析RePKG:Wallpaper Engine资源解包与纹理转换技术实现