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

发布时间:2022-04-21 09:08:28 作者:iii
来源:亿速云 阅读:217

这篇“Spring Boot怎么正确读取配置文件属性”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“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怎么正确读取配置文件属性”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注亿速云行业资讯频道。

推荐阅读:
  1. Spring怎么读取配置文件属性
  2. 怎么在Spring Boot中读取resources目录文件

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

springboot

上一篇:Rainbond网络治理插件ServiceMesh怎么用

下一篇:C#连续任务Task.ContinueWith方法怎么用

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》