1. 程式人生 > 其它 >@ConfigurationProperties(prefix = "server-options") 丟擲 SpringBoot Configuration Annotation Processor not configured 錯誤

@ConfigurationProperties(prefix = "server-options") 丟擲 SpringBoot Configuration Annotation Processor not configured 錯誤

說明

spring-boot-configuration-processor 包的作用是自動生成 META-INF/spring-configuration-metadata.json 檔案,而這個 json 檔案可以為我們在配置 application.yml 檔案時提供智慧提示、自動補全、註釋功能。
這樣一來,在開發過程中就會避免寫錯配置項的問題,也可以增加編碼流暢感

完美整合步驟

  1. 在 pom.xml 的 dependencies 節點中加入 spring-boot-configuration-processor 包的 maven 依賴

      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-configuration-processor</artifactId>
          <optional>true</optional>
          <version>2.5.2</version>
      </dependency>
    
  2. 檢查有沒有在 pom.xml 中配置 build/plugins/[artifactId=maven-compiler-plugin]/configuration/annotationProcessorPaths
    如果沒有配置,可以跳到第 3 點了
    如果配置了,那麼一定要在 annotationProcessorPaths 加入 spring-boot-configuration-processor 包的 path 節點,如下:

      <path>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-configuration-processor</artifactId>
        <version>2.5.2</version>
      </path>
    

    注意 versiondependencies 節點中的一致,可以在 properties 節點中宣告該包的版本號,然後在以上兩個地方引用宣告的變數

  3. 編寫自己的 XXProperty,如下:

    package com.example.springboottests;
    
    import lombok.Getter;
    import lombok.Setter;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.boot.context.properties.NestedConfigurationProperty;
    import org.springframework.stereotype.Component;
    
    @Getter
    @Setter
    @Component
    @ConfigurationProperties(prefix = "server-options")
    public class ServerProperty {
        /**
         * 名稱
         */
        private String name;
    
        /**
         * 其他配置
         */
        @NestedConfigurationProperty
        private ServerOtherProperty api;
    
        @Getter
        @Setter
        public static class ServerOtherProperty {
            /**
             * 標題
             */
            private String title;
        }
    }
    
  4. 完畢,現在可以去 resources/application.yml 檢視效果了

必讀的注意事項:

  1. 每次修改 ServerProperty 中的內容時,必須要 rebuild 專案,因為他是通過編譯幫助我們自動生成 META-INF/spring-configuration-metadata.json 檔案,所以如果不 rebuild,json 檔案內容就不會變。
  2. 如果不生效,可以自己看下是不是修改了 pom.xml 但沒有點選右上角的重新整理按鈕,或者刪除 target 目錄再 build 試試