直接上编译时发生的错误
Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'spring.redis.cache.on' in value "${spring.redis.cache.on}"
yml文件部分配置:
spring:
#--------------------------------------------------
# DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
#--------------------------------------------------
cache:
type: redis
redis:
host: localhost
port: 6379
password: null
pool:
# 最大连接数
max-active: 100
# 最大空闲数,空闲链接数大于maxIdle时,将进行回收
max-idle: 8
# 最小空闲数,低于minIdle时,将创建新的链接
min-idle: 0
# 最大等待数
max-wait: 100000
timeout: 0
database: 0
# 自定义的要获取的配置
cache:
on: true
@Value获取配置文件配置部分代码
@Aspect
@Component
public class RedisCacheAspect {
@Autowired
private RedisTemplate redisTemplate;
/**
* 是否开启redis缓存,将查询的结果写入value
*/
@Value(value = "${spring.redis.cache.on}")
private Boolean isOn =true;
//此处省略其它代码
}
按照官方给出的方式进行@Value方式获取,应该是没有问题的,那么问题出在哪里呢?
测试一:我们将上面的配置文件.yml换成.properties,@Value获取配置的方式不变,如下:
#--------------------------------------------------
# DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
#--------------------------------------------------
spring.cache.type=redis
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=null
spring.redis.pool.max-active=100
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0
spring.redis.pool.max-wait=100000
spring.redis.database=0
# 自定义的要获取的配置
spring.redis.cache.on=true
经过测试,发现程序可以正常编译通过,并通过Debug测试发现值可以正常获取。
测试二:我们将上面的配置文件.yml中所配置的on属性修改为ison,@Value获取配置的方式相应修改为@Value(value = "${spring.redis.cache.ison}")。如下:
#--------------------------------------------------
# DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
#--------------------------------------------------
spring.cache.type=redis
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=null
spring.redis.pool.max-active=100
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0
spring.redis.pool.max-wait=100000
spring.redis.database=0
# 自定义的要获取的配置
spring.redis.cache.ison=true
经测试后,发现程序可以正常编译通过,并通过Debug测试发现值可以正常获取。
结论:在我们使用yml进行自定义配置项时,要注意配置项的名称,我们推测可能使用on作为配置项名称涉及到了yml配置文件的关键字,导致无法正常解析配置项,如有知道原因的欢迎下方留言,一起讨论。
另外,使用.properties文件和.yml文件作为配置文件使用@Value获取配置项时,还存在一点区别:
在IDEA中测试发现,当使用.properties文件时,按下Ctrl鼠标放在${spring.redis.cache.ison}上是可以定位到配置文件的位置的。但是使用.yml文件,做相同操作时无法定位到相应的配置文件位置。不过二者都是可以正常使用的,只是IDEA支持上面的区别而已。