zoukankan      html  css  js  c++  java
  • 【SpringBoot】【3】读取配置文件中的参数并配置给全局使用

    前言:

    读取配置文件参数的方法:@Value("${xx}")注解。但是@Value不能为static变量赋值,而且很多时候我们需要将参数放在一个地方统一管理,而不是每个类都赋值一次。

    正文:

    注意:一定要给类加上@Component 注解

    application.xml

    test:
      app_id: 12345
      app_secret: 66666
      is_active: true

    统一读取配置文件参数:

    package com.example.demo.config;
    
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    public class YxConfig {
        public static String appId;
    
        public static String appSecret;
    
        public static boolean isActive;
    
        @Value("${test.app_id}")
        public void setAppId(String param) {
            appId = param;
        }
    
        @Value("${test.app_secret}")
        public void setAppSecret(String param) {
            appSecret = param;
        }
    
        @Value("${test.is_active}")
        public void setIsActive(boolean param) {
            isActive = param;
        }
    
    }

    测试类:

    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class YxConfigTest {
        @Test
        public void test() {
            System.out.print("app_id:" + YxConfig.appId + "; ");
            System.out.print("app_secret:" + YxConfig.appSecret+ "; ");
            System.out.print("is_active:" + YxConfig.isActive);
        }
    }

    结果:

    参考博客:

    SpringBoot 中使用 @Value 为 static 变量赋值 - 简书
    https://www.jianshu.com/p/ea477fc9abf7

  • 相关阅读:
    script 执行顺序
    webpack 引入外部资源 webpack-require-http runtime-import
    react dnd
    require.contex 自动话引入
    git rebase
    文档在线转化
    moment 多语言 包问题
    Python 修改在使用ddt时测试报告默认显示用例名称与预期不符
    Robot Framework:随机数
    Robot Framework:变量与运算
  • 原文地址:https://www.cnblogs.com/huashengweilong/p/12004045.html
Copyright © 2011-2022 走看看