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

@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.Driverurl=jdbc:mysql://localhost:3306/abc?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=falseusername=rootpassword=admin

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

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

如:

jdbc.driver=com.mysql.cj.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/abc?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=falsejdbc.username=rootjdbc.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

正确的寒暄必须在短短一句话中明显地表露出你对他的关怀。

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

相关文章:

你感兴趣的文章:

标签云: