使用常量配置类替换硬编码常量

业务中有时候需要配置一些常量,一般是直接新建一个常量类Constant,然后再里面需要用的常量。需要用时直接用类名加属性名的方式使用,例如

public class Constant{
    public static final String TOKNE_PREFIX="test::"
}

public class service{
    public void test(){
        System.out.println(Constant.TOKNE_PERFIX)
    }
}

但是这种形式的一个弊端就是如果现在项目上线了需要修修改其中的一个常量的配置,那么久需要去修改类。服务要重新启动,那么此时可以使用基于配置文件的方式进行,然后结合注册中心对配置文件进行动态刷新即可,具体步骤如下

导入相应的依赖,因为使用@ConfigurationProperties注解,根据官方提示需要引入对应的处理器

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-configuration-processor</artifactId>
   <optional>true</optional>
</dependency>

<!--配置插件-->
<project>
   <build>
       <plugins>
           <plugin>
               <groupId>org.springframework.boot</groupId>
               <artifactId>spring-boot-maven-plugin</artifactId>
               <configuration>
                   <excludes>
                       <exclude>
                           <groupId>org.springframework.boot</groupId>
                           <artifactId>spring-boot-configuration-processor</artifactId>
                       </exclude>
                   </excludes>
               </configuration>
           </plugin>
       </plugins>
   </build>
</project>

1.编写常量配置文件application-constant.yaml

constant:
#驼峰命名格式,对应的属性名称就是tokenPrefix
	token-prefix: "test::"

2.在主配置文件中引入常量配置文件

spring:
profiles:
include:
constant #直接使用后缀即可

3.编写常量配置类

@Component
@ConfigurationProperties(prefix = "constant")
@Data//这里使用lombok,也可以自己创建属性对应的get和set方法
public class ConstantConfig{
   private String tokenPrefix;
}

4.通过Spring依赖注入的方式进行访问

@RestController
public class test{
   @Resource
   private ConstantConfig constant;

   @GetMapping("/test")
   public String test(){
       return constant.getTokenPrefiix();
   }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值