本篇文章將會講解在springboot項目中如何實現自定義配置以及在IDEA或者Eclipse中實現配置項提示,就像spring的配置提示一樣
想要做到這點其實非常簡單
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倉庫,就會有提示了
而且,如果properties類字段有注釋,IDEA中也會有注釋對配置的字段進行說明。在我的例子中為了不影響閱讀,已經刪除注釋,如果想要注釋,一定不要使用單行注釋,使用多行注釋是規范。
6.參考文檔
https://www.mdoninger.de/2015/05/16/completion-for-custom-properties-in-spring-boot.html