我们在开发中通常会遇到定义常量,但是如果写在java代码里不利于优化,于是这里我们将常量定义在配置文件里,步骤如下;
1.在配置文件application.yml定义常量
aliyun: oss: file: endpoint: oss-cn-shanghai.aliyuncs.com keyid: LTAIsOB7X12kCHTGX81 keysecret: ASy5lz2Mwr5KIVEUY3eDhFFi2jD1RkPC bucketname: eric.fang
2.创建一个类实现InitializingBean接口,重写afterPropertiesSet()方法,加上@component注解,定义变量,使用@Value注解将值注入,然后定义常量方便访问,最后让常量赋值
@Componentpublic class ConstantPropertiesUtil implements InitializingBean { @Value("${aliyun.oss.file.endpoint}")private String endpoint; @Value("${aliyun.oss.file.keyid}")private String keyid; @Value("${aliyun.oss.file.keysecret}")private String keysecret; @Value("${aliyun.oss.file.bucketname}")private String bucketname;//定义常量,为了能够使用public static String ENDPOINT; public static String KEYID; public static String KEYSECRET;public static String BUCKEYNAME; @Overridepublic void afterPropertiesSet() throws Exception { ENDPOINT=endpoint; KEYID=keyid; KEYSECRET=keysecret; BUCKEYNAME=bucketname; } }
3.可以通过类直接进行调用
列如:
ConstantPropertiesUtil.ENDPOINT