千家信息网

Spring Boot怎么正确读取配置文件属性

发表于:2025-11-11 作者:千家信息网编辑
千家信息网最后更新 2025年11月11日,这篇"Spring Boot怎么正确读取配置文件属性"文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一
千家信息网最后更新 2025年11月11日Spring Boot怎么正确读取配置文件属性

这篇"Spring Boot怎么正确读取配置文件属性"文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇"Spring Boot怎么正确读取配置文件属性"文章吧。

    @Value

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

    示例代码

    application.yml文件中属性:

    //定义属性fileName : testisFile : falsefilePath : c://test

    @value读取application.yml属性值:

    @Configurationpublic 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不能将属性值读取静态变量,否则读取的值为空。

    • @Value不能将属性值读取常量,否则读取的值为空。

    • @Value不能读取boolean类型的值,经过测试Spring Boot2.1的版本是无效的,2.2以上版本支持。

    所以个人建议非必要情况,尽量少用@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; }

    特别注意:

    • 默认情况不会将实体注入到spring的容器中,需要结合@EnableConfigurationProperties或者@Component一起使用,否则注入对象为空。

    @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=222user.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怎么正确读取配置文件属性"这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注行业资讯频道。

    0