热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

在SpringBoot项目中通过YAML配置文件为静态变量设置值的方法与实践

在SpringBoot项目中,通过YAML配置文件为静态变量设置值的方法与实践涉及以下几个步骤:首先,创建一个新的配置类。需要注意的是,自动生成的setter方法默认是非静态的,因此需要手动将其修改为静态方法,以确保静态变量能够正确初始化。此外,建议使用`@Value`注解或`@ConfigurationProperties`注解来注入配置属性,以提高代码的可读性和维护性。

1、新建一个配置类


注意点:

自动生成的setter方法是静态的,要将static删除掉
自动生成的setter方法是静态的,要将static删除掉
自动生成的setter方法是静态的,要将static删除掉

package com.yt.config;import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;import lombok.Getter;/*** 短信* @author tyg* @date 2020年8月4日上午11:44:36*/
@Getter
@Component // 这里必须加,不然使用AliyunConfig.accessSecret获取到的为null
@ConfigurationProperties(prefix = "aliyun.sms")
public class SmsConfig {/** 短信发送开关,测试环境配置为false,就不发送短信 */public static Boolean smsFlag;@Value("${aliyun.sms.sms-flag}") // 注意这里是全路径哈public void setSmsFlag(Boolean smsFlag) {SmsConfig.smsFlag = smsFlag;}
}

2、配置application.yml

aliyun:sms:#短信开关,测试时可配置为falsesms-flag: true

3、测试类

package com.yt;import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;import com.yt.config.SmsConfig;/*** 测试类* @author tyg* @date 2020年8月7日下午5:04:49*/
@SpringBootTest
class TmouseApplicationTests {@Testvoid test2() {System.out.println(SmsConfig.smsFlag);}
}

4、最后效果在这里插入图片描述


推荐阅读
author-avatar
文静的疯子19__97
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有