springBoot中static静态工具方法获取配置文件属性值
参考网址:
https://mp.weixin.qq.com/s/iOWdDnPt5aQaHR9gRjwtAA
http://www.shaoming.club/archives/springboot%E5%90%AF%E5%8A%A8%E6%97%B6%E8%AE%A9%E6%96%B9%E6%B3%95%E8%87%AA%E5%8A%A8%E6%89%A7%E8%A1%8C%E7%9A%84%E5%87%A0%E7%A7%8D%E5%AE%9E%E7%8E%B0%E6%96%B9%E5%BC%8Fmd
需求
定义全局常量
旧的方案
在项目中定义一个常量类或者常量接口
public class AppConstant {
public static final String key = "f165bad5-c0da-43f9-a983-b86af1e0c266";
}
新的方案1
写了一个读取配置文件的类
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
/*
说明:
使用@Configuration和@Component注解都是可以的
*/
//@Configuration
@Component
public class QiNiuCloudConfiguration {
public static String accessKey;
@Value("${qinNiuCloud.ACCESS_KEY}")
private String tempAccessKey;
// 该注解是关键
@PostConstruct
public void setAccessKey() {
accessKey = this.tempAccessKey;
}
}
在application.properties添加属性配置
qinNiuCloud.ACCESS_KEY=f165bad5-c0da-43f9-a983-b86af1e0c266
新的方案2
写了一个读取配置文件的类
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/*
说明:
使用@Configuration和@Component注解都是可以的
*/
//@Configuration
@Component
public class QiniuyunStaticConfiguration implements InitializingBean {
public static String ACCESS_KEY;
@Value("${qinNiuCloud.ACCESS_KEY}")
private String accessKey;
@Override
public void afterPropertiesSet() throws Exception {
ACCESS_KEY = accessKey;
}
}
测试
三种方式定义项目中常量
建议使用新的方案1,2,因为这两种方式比较灵活,可以在配置文件中指定项目常量
在启动类中测试,获取常量
import com.example.demo.constant.AppConstant;
import com.example.demo.constant.QiNiuCloudConfiguration;
import com.example.demo.constant.QiniuyunStaticConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(DemoApplication.class, args);
System.out.println("定义全局常量类获取常量,常量的值为: "+AppConstant.APP_KEY);
System.out.println("定义读取配置文件属性值的类,使用@PostConcust注解的方式,常量的值为: "+QiNiuCloudConfiguration.accessKey);
System.out.println("定义读取配置文件属性值的类,使用实现InitializingBean接口的方式,常量的值为: "+QiniuyunStaticConfiguration.ACCESS_KEY);
}
}
控制台打印
f165bad5-c0da-43f9-a983-b86af1e0c266
f165bad5-c0da-43f9-a983-b86af1e0c266
f165bad5-c0da-43f9-a983-b86af1e0c266
个人csdn博客网址:https://blog.csdn.net/shaoming314
个人博客网址:www.shaoming.club
个人gitee地址:https://gitee.com/shao_ming314/note
勇敢牛牛,不怕困难
存中…(img-tMnT6pne-1628736274481)]
个人gitee地址:https://gitee.com/shao_ming314/note
[外链图片转存中…(img-J9r9WxRh-1628736274484)]
勇敢牛牛,不怕困难