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

网友投稿 233 2022-08-03


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

目录前言@Value示例代码@ConfigurationProperties示例代码@EnableConfigurationProperties@ConfigurationPropertiesScan@PropertySource示例代码总结

前言

项目中经常会经常读取配置文件中的属性的值,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不能将属性值读取静态变量,否则读取的值为空。@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=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"}

总结

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


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Spring Boot 集成PageHelper的使用方法
下一篇:如何通过源码了解Java的自动装箱拆箱详解(Java自动拆箱)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~