1. 程式人生 > >使用@Value讀取yml配置檔案編譯報錯

使用@Value讀取yml配置檔案編譯報錯

直接上編譯時發生的錯誤

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支援上面的區別而已。