1. springboot如何获取配置文件的配置?
  2. springboot如何在静态类中获取配置?

以下所有示例都通过验证。

1.定义配置文件格式

这里主要指常见的配置文件:properties, yaml.

当然,json也可以作为配置,不过不是首选。

使用的配置文件:

application.properties

api.key=jimo
api.password=password

application.yml

api:username: admin

2.动态注入加载

2.1 @Value

@Component
public class ApiConfig {@Value("${api.key}")private String key;@Value("${api.username}")private String username;@Value("${api.password}")private String password;
}

2.2 @ConfigurationProperties(prefix = “api”)

@Component
@ConfigurationProperties(prefix = "api")
public class ApiConfig {private String key;private String username;private String password;
}

2.3 指定配置文件@PropertySource

@PropertySource是spring提供的一个注解,用于把特定配置加载到Environment环境变量里,标准用法是和Configuration一起使用。

注意:@PropertySource(value = {"classpath:test.conf"})对于同一个文件,只需要在一个地方注册,其他地方都可以使用了。

比如:在主类注册

@PropertySource(value = {"classpath:test.conf"})
@SpringBootApplication
public class ConfigTestApplication {public static void main(String[] args) {SpringApplication.run(ConfigTestApplication.class, args);}
}

在其他所有bean里都可以使用:

@Component
public class Api {@Value("${test.a}")private String a;@Value("${test.b}")private String b;
}

另外:@Value@ConfigurationProperties 都是可以和@PropertySource组合使用的,只是注意配置的重复导致覆盖问题(后加载的会覆盖前面的).

@Data
@Component
@PropertySource(value = {"classpath:test.conf"})
public class Api4Config {@Value("${test.a}")private String a;@Value("${test.b}")private String b;
}

3.静态加载

指在静态类中读取配置文件内容

3.1 直接读取

3.1.1 Properties

我们可以使用最基础的Properties工具类:这是java的方式

import java.io.IOException;
import java.util.Properties;
import org.springframework.core.io.ClassPathResource;/*** 直接读取配置文件** @author jimo* @version 1.0.0*/
public class RawConfigUtil {private static Properties properties = readProperties("test.conf", "test2.conf");private static Properties readProperties(String... confFile) {final Properties properties = new Properties();try {for (String path : confFile) {final ClassPathResource resource = new ClassPathResource(path);properties.load(resource.getInputStream());}} catch (IOException e) {e.printStackTrace();}return properties;}public static String getString(String key) {return properties.getProperty(key);}
}

3.1.2 typesafe.config

或者通过第三方工具:https://github.com/lightbend/config读取

        <dependency><groupId>com.typesafe</groupId><artifactId>config</artifactId><version>1.4.0</version></dependency>

代码:

import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;/*** @author jimo* @version 1.0.0*/
public class ConfigUtils {private static Config load;// 默认加载classpath下的application.*static {load = ConfigFactory.load();}/*** 读取配置文件中指定Key的值** @param key 配置文件中的key* @return 指定key的value*/public static String getString(String key) {return load.getString(key);}/*** 读取配置文件中指定Key的值** @param key 配置文件中的key* @return 指定key的value*/public static int getInt(String key) {return load.getInt(key);}/*** 读取配置文件中指定Key的值** @param key 配置文件中的key* @return 指定key的value*/public static boolean getBoolean(String key) {return load.getBoolean(key);}}

根据其介绍,默认可以加载这些配置文件:

system properties
application.conf (all resources on classpath with this name)
application.json (all resources on classpath with this name)
application.properties (all resources on classpath with this name)
reference.conf (all resources on classpath with this name)

比较特别的是可以读取json配置,不过笔者用得不多。

3.1.3 小结

但是,这2种方式有以下缺点:

  1. 都不能读取yaml格式的配置
  2. 不能利用springboot从外部和环境变量加载配置的功能,所以只能是死的配置,不够灵活

3.2 使用Environment

要针对spring环境,还是用spring的工具。

Environment是在Spring中代表当前运行的环境,包括:profilesproperties,
它继承了PropertyResolver接口所以才具有读取配置的功能:

public interface Environment extends PropertyResolver {...}

所以,配置的实现其实是PropertyResolver接口的实现类做的。

如果我们能在静态类里持有这个环境,那么就可以获取变量了,恰好spring就提供了这样的接口:EnvironmentAware.

public interface EnvironmentAware extends Aware {/*** Set the {@code Environment} that this component runs in.*/void setEnvironment(Environment environment);
}

这个接口就一个方法:当环境准备好时,会调用这个接口的实现类,然后设置实例。

所以,我们实现这个接口得到Environment:

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;/*** @author jimo* @version 1.0.0*/
@Slf4j
@Component
public class MyEnvBeanUtil implements EnvironmentAware {private static Environment env;@Overridepublic void setEnvironment(Environment environment) {env = environment;}public static String getString(String key) {return env.getProperty(key);}
}

我们实际调用时:

    @Testvoid testEnv() {assertEquals("password", MyEnvBeanUtil.getString("api.password"));assertEquals("admin", MyEnvBeanUtil.getString("api.username"));}

3.3 继承PropertySourcesPlaceholderConfigurer

PropertySourcesPlaceholderConfigurer实现了EnvironmentAware,所以更加丰富,因为可以设置占位符这些信息,用于自定义占位符使用这个,使用方法

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.ConfigurablePropertyResolver;
import org.springframework.core.env.PropertyResolver;
import org.springframework.stereotype.Component;/*** @author jimo* @version 1.0.0*/
@Component
public class PropertyUtil extends PropertySourcesPlaceholderConfigurer {private static PropertyResolver propertyResolver;@Overrideprotected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess,ConfigurablePropertyResolver propertyResolver) throws BeansException {super.processProperties(beanFactoryToProcess, propertyResolver);PropertyUtil.propertyResolver = propertyResolver;}public static String getString(String key) {return propertyResolver.getProperty(key);}
}

4.总结

本文对spring获取配置做了一些总结,主要有以下方式获取spring的配置:

  1. @Value
  2. @ConfigurationProperties
  3. @PropertySource指定配置文件
  4. Properties读取
  5. typesafe.config读取
  6. EnvironmentAware
  7. PropertySourcesPlaceholderConfigurer

后续会总结springboot的多环境配置。

springboot如何在静态类中获取配置-配置获取全解相关推荐

  1. 【SpringBoot零基础案例09】【IEDA 2021.1】SpringBoot将核心配置文件中的自定义配置映射到一个对象

    使用@Value注解获取核心配置文件中的值时只能是一个一个的获取,如果在配置文件中有多个对象需要用到名称一样的配置,如name.age等属性,则需要区分是这个属性是哪个对象的.因此可以将这些配置映射到 ...

  2. redis.conf 7.0 配置和原理全解,生产王者必备

    我是 Redis, 当程序员用指令 ./redis-server /path/to/redis.conf 把我启动的时候,第一个参数必须是redis.conf 文件的路径. 这个文件很重要,就好像是你 ...

  3. python基础系列教程——python中的字符串和正则表达式全解

    全栈工程师开发手册 (作者:栾鹏) python教程全解 转义字符 正则表达式是建立在字符串的基础上,当需要在字符中使用特殊字符时,python用反斜杠\转义字符.如下表: 转义字符 描述\(在行尾时 ...

  4. c#获取网页源码全解

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...

  5. 深度学习中的轴/axis/dim全解

    在深度学习中,轴,指的就是张量的层级,一般通过参数axis/dim来设定.很多张量的运算.神经网络的构建,都会涉及到轴,但到底取哪个轴,却不是那么容易把握. 下面会针对轴/axis/dim,基于 Py ...

  6. 机器学习 | Sklearn中的朴素贝叶斯全解

    前期文章介绍了朴素贝叶斯理论,掌握理论后如何去使用它,是数据挖掘工作者需要掌握的实操技能,下面来看看Sklearn中都有哪些朴素贝叶斯. 朴素贝叶斯是运用训练数据学习联合概率分布 及 ,然后求得后验概 ...

  7. SpringBoot中通过@Value获取自定义配置的值

    场景 在SpringBoot项目中的application.properties中定义变量,要在 controller中获取自定义配置的值. 实现 打开 application.properties ...

  8. 【SpringBoot零基础案例08】【IEDA 2021.1】SpringBoot获取核心配置文件application.properties中的自定义配置

    新建模块 在配置文件中进行自定义的配置 在java代码中使用@Value("${属性名}")来获取自定义配置的值,这个注解的位置不是固定的,可以在任何需要用到自定义值的地方使用 I ...

  9. 在kotlin companion object中读取spring boot配置文件,静态类使用@Value注解配置

    在kotlin companion object中读取配置文件 静态类使用@Value注解配置 class Config {@Value("\${name}")fun setNam ...

最新文章

  1. 为什么数据线easy糟糕
  2. 自学python需要下载什么软件-学python下载什么软件开发
  3. minheight能继承吗_CSS 哪些属性默认会继承, 哪些不会继承?
  4. java获取系统运行日志文件_java – 如何获取特定的日志文件并在jenkins控制台输出中显示其内容...
  5. pow(x,n) leecode
  6. 在阿里淘系6个月能有哪些收获成长?
  7. C++ 运算符重载规则
  8. 移动开发在路上-- IOS移动开发系列 多线程三
  9. 三星GalaxyS21或取消附赠有线耳机:捆绑卖新款无线耳机
  10. 操作es_ES打野皇子操作看呆Uzi:这哥们肯定是深得Lucky真传
  11. 如何理解Spring对缓存的支持
  12. 谷歌修复 Chrome 站点隔离绕过漏洞
  13. 霍夫曼编码实验matlab,哈夫曼编码 MATLAB程序
  14. linux gradle目录结构,android studio中,project和module的目录结构
  15. java反射机制历史_java的反射机制浅谈
  16. 【UVA10256】The Great Divide(凸包相离判定)
  17. OBS录屏软件使用指南
  18. 路由器刷机教程图解_路由器刷固件图文教程,刷机OpenWrt第三方固件,路由器升级固件...
  19. 生理学知识点总结--biologic
  20. c语言分桃分题设计思路,C语言实现的猴子分桃问题算法解决方案

热门文章

  1. canvas 画背景图以及文字换行的写法
  2. 基于事件驱动的微服务教程
  3. 【读书笔记】真相推理师-凶宅
  4. Visual Studio 2019安装 ReportViewer 教程
  5. move upload file php,php文件上传move_uploaded_file函数
  6. mysql数据库连接等待时间修改
  7. MyBatis报无效的列索引的错误
  8. Oracle12c impdp导入慢的问题
  9. hive explode 使用
  10. 设计模式学习笔记十七(迭代器设计模式)