SpringBoot自定義配置以及IDEA配置提示


本篇文章將會講解在springboot項目中如何實現自定義配置以及在IDEA或者Eclipse中實現配置項提示,就像spring的配置提示一樣

image-20210420142719125

想要做到這點其實非常簡單

1.添加依賴

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

2.啟用注解

在配置文件類上添加EnableConfigurationProperties注解,如下所示

@Configuration
@EnableConfigurationProperties
public class Config {

}

3.新增配置文件

以xxl配置為例新增如下配置文件

xxl:
  job:
    admin:
      addresses: http://127.0.0.1:8080/xxljob
    accessToken:
    executor:
      appname: my-app-name
      logpath: ./logs
      logretentiondays: 30

4.根據配置文件新建配置類

@Component
@Data
@ConfigurationProperties(prefix= "xxl.job")
public class XxlJobProperty {
    private String accessToken;
    private XxlJobAdminProperty admin;
    private XxlJobExecutor executor;
}
@Component
@Data
@ConfigurationProperties(prefix= "xxl.job.admin")
public class XxlJobAdminProperty {
    /**
     * xxl-job admin address list, such as "http://address" or "http://address01,http://address02"
     */
    private String addresses;
}
@Data
@Component
@ConfigurationProperties(prefix= "xxl.job.executor")
public class XxlJobExecutor {
    private String appname;
    private String address;
    private String ip;
    private Integer port;
    private String logpath;
    private Integer logretentiondays;
}

5.運行命令mvn clean install

昨晚上述四步驟之后,在IDEA環境中會發現並不會配置提示,spring的配置有提示是因為它們是作為外部依賴的jar包保存在了本地的maven倉庫,IDEA就能根據其作出配置提示,所以運行mvn clean install 命令將項目直接安裝到本地maven倉庫,就會有提示了

image-20210420143659778

而且,如果properties類字段有注釋,IDEA中也會有注釋對配置的字段進行說明。在我的例子中為了不影響閱讀,已經刪除注釋,如果想要注釋,一定不要使用單行注釋,使用多行注釋是規范。

image-20210420144242323

6.參考文檔

https://docs.spring.io/spring-boot/docs/2.4.5/reference/html/appendix-configuration-metadata.html#configuration-metadata-annotation-processor

https://www.mdoninger.de/2015/05/16/completion-for-custom-properties-in-spring-boot.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM