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

posted @ 2021-04-20 14:50  狂盗一枝梅  阅读(1132)  评论(0编辑  收藏  举报