解决使用@Value(${×××))从properties文件取值的坑

来自:网络
时间:2021-08-09
阅读:

@Value(${×××))从properties文件取值

前提:

你的实体类已经加入到了IOC容器中(使用@Compenet等注解)

报错代码:

@Value("${driver}")
private String driver;
@Value("${url}")
private String url;
@Value("${username}")
private String userName;
@Value("${password}")
private String password;

properties文件

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/abc?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
username=root
password=admin

此时你这样写 @Value 注解是无法获取 properties文件中的值的

必须要在properties文件属性前加上前缀(任意)即可

如:

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/abc?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
jdbc.username=root
jdbc.password=admin

对应的类也要修改

@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String userName;
@Value("${jdbc.password}")
private String password;

这样就可以正常获取了

补充:

1、静态变量无法注入

2、Springboot默认属性文件是application.properties

Spring @Value("${}")空值处理

场景:

Test类中有一个在application.properties配置的属性email

@Value("${email}")
private String email;

如果email在配置中没有配置,应用启动时将报找不到该属性异常,导致启动失败。

解决方案1:

在Test类上同时加上@Component,@Lazy

解决方案2:

在springboot中提供了@ConditionalOnProperty注解

设置注入条件

@ConditionalOnProperty(name = "flag", havingValue = "true")

仅当配置文件application.properties中flag属性为true时才会实例化bean

返回顶部
顶部