业务中有时候需要配置一些常量,一般是直接新建一个常量类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(); } }