【Spring Boot採坑記】- 自定義配置之 @ConfigurationProperties 和 @EnableConfigurationProperties

1. 首先

自定義bean,配置 setter&getter ,使用 @ConfigurationProperties 註解配置bean類

有如下提示:

Not registered via @EnableConfigurationProperties, marked as Spring component, or scanned via @ConfigurationPropertiesScan

解決:

添加 @Component 註解即可

2.然後

有如下提示,且 Ctrl+左鍵 點擊配置項不能跳轉

Spring Boot Configuration Annotation Processor not configured

解決:

pom 添加如下依賴即可

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
        </dependency>

此時可能會出現如下提示,可以忽略

Re-run Spring Boot Configuration Annotation Processor to update generated metadata

3.其次

主類配置 @EnableConfigurationProperties 註解,此時點擊配置文件即可跳轉,且輸入自定義配置時IDE會自動提示

4.最後

如果只自定義了配置項,但是不想定義對應的bean,可以在註解中通過${}引用配置,例如

@Scheduled(cron = "${timer.async-time-task}")

有如下缺點:

  • IDE不會自動提示配置項
  • 配置文件顯示黃色 警告
  • Ctrl+左鍵點擊配置項不會跳轉

注:以上流程只測試了 IntelliJ IDEA,其他 IDE 暫未測試

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章