首页 > 编程技术 > java

Spring Boot 如何正确读取配置文件属性

发布时间:2022-4-20 19:23 作者:剑圣无痕 

前言

项目中经常会经常读取配置文件中的属性的值,Spring Boot提供了很多注解读取配置文件属性,那么如何正确使用呢?

@Value

@Value用来读取application.yml配置文件中属性的值。

示例代码

application.yml文件中属性:

//定义属性
fileName : test
isFile : false
filePath : c://test

@value读取application.yml属性值:

@Configuration
public class FileConfig
{
    @Value("${fileName}")
    private final String fileName;
    @Value("${isFile}")
    private boolean isFile;
    @Value("${filePath}")
    private static String filePath;
}

测试:

 @Autowired
    private FileConfig fileConfig;
    @GetMapping("getFileConfig")
    public void getFileConfig()
    {
        logger.info("fileConfig:{}",fileConfig);
    }

运行结果:

fileConfig:FileConfig [fileName=, isFile=false, filePath=null]

特别注意:

所以个人建议非必要情况,尽量少用@Value注解读取属性值。

@ConfigurationProperties

读取配置文件值并且转换成类对象,便于获取值和修改属性值。

示例代码

application.yml文件中属性:

http:
  pool:
    # 连接超时
    connectTimeout: 5000
    #获取连接池中连接超时
    connectionRequestTimeout: 1000
    #每个路由连接数量
    defaultMaxPerRoute: 50
    # /连接池中最大连接数
    maxTotal: 50
    # 服务器返回数据(response)的时间
    socketTimeout: 5000
    #定义不活动的时间(以毫秒为单位),连接回收
    validateAfterInactivity: 30000      

@ConfigurationProperties读取application.yml中以http.pool开头的属性值:

//以http.pool开头
@Component
@ConfigurationProperties(prefix = "http.pool")
public class HttpClientConfig implements Serializable
{
    private static final long serialVersionUID = -4608251658338406043L;
    /**
     * 最大连接数
     */
    private Integer maxTotal;
    /**
     * 路由是对最大连接数的细分
     * 每个路由基础的连接数
     */
    private Integer defaultMaxPerRoute;
    /**
     * 连接超时时间
     */
    private Integer connectTimeout;
    /**
     * 从连接池中获取连接的超时时间
     */
    private Integer connectionRequestTimeout;
    /**
     * 服务器返回数据(response)的时间
     */
    private Integer socketTimeout;

测试:

  @GetMapping("getHttpClientConfig")
    public void getHttpClientConfig()
    {
        String json=FastJsonUtil.toJSONString(httpClientConfig);
        logger.info("fileConfig:{}",json);
    }

属性嵌套:

@ConfigurationProperties 可以嵌套List、map、class

config:
  url:http://localhsot:8080
  gaode-map:
    host: https://restapi.amap.com/v3
    key: 1234
@ConfigurationProperties(prefix="config")
public class Config
{
    //高德地图信息
    private GaodeMap gaodeMap;
 }

特别注意:

@EnableConfigurationProperties

@ConfigurationProperties读取对象注入到spring容器中。例如上述示例也可以采用@EnableConfigurationProperties 来注入

@EnableConfigurationProperties(HttpClientConfig.class)
public class FileController
{
    private Logger logger = LoggerFactory.getLogger(FileController.class);
    @Autowired
    private FileConfig fileConfig;
    @GetMapping("getHttpClientConfig")
    public void getHttpClientConfig()
    {
        String json=FastJsonUtil.toJSONString(httpClientConfig);
        logger.info("fileConfig:{}",json);
    }
  }

@ConfigurationPropertiesScan

用来扫描@ConfigurationProperties实体类并将类注入到Spring容器,上述示例可以如下使用

@ConfigurationPropertiesScan("com.xx.fw.config")
public class FwCoreApplication
{
    public static void main(String[] args)
    {
        SpringApplication.run(FwCoreApplication.class, args);
    }
}

@PropertySource

@PropertySource 主要用于读取指定的配置文件,需要结合@ConfigurationProperties 注解一起使用实现配置文件和Java Bean的注入操作。

示例代码

属性文件user.properteis:

user.id=222
user.name=剑圣
user.age=28

实体类定义:

@Component
@ConfigurationProperties(prefix = "user")
@PropertySource(value = {"classpath:user.properties"})
public class UserConfig 
{
    private String id;
    private String name;
    private int age;
 }

测试:

    @GetMapping("getUserConfig")
    public void getUserConfig()
    {
        String json=FastJsonUtil.toJSONString(userConfig);
        logger.info("userConfig:{}",json);
    }

输出结果:

c.s.fw.controller.FileController - userConfig:{"age":28,"id":"123","name":"admin"}

总结

重点讲解了通过各种注解读取配置文件种属性值,每种方式都是各自的优缺点,项目中一定要统一规范使用,便于项目维护和排查问题。

到此这篇关于Spring Boot 如何正确读取配置文件属性的文章就介绍到这了,更多相关Spring Boot 读取文件属性内容请搜索猪先飞以前的文章或继续浏览下面的相关文章希望大家以后多多支持猪先飞!

原文出处:https://juejin.cn/post/7087962181924454413

标签:[!--infotagslink--]

您可能感兴趣的文章: