2

我正在尋找解決方案來創建我的應用程序中使用的彈簧配置屬性的文檔。記錄彈簧(引導)配置屬性

例如,我使用application.properties文件中屬性'person.age'來設置人的年齡,類'Person'具有以下定義。

public class Person { 
    @Value("${person.age:21}") 
    private int age; 

    public Person(){} 

    private int getAge(){ return age; } 
} 

我想有什麼,是一個文檔,說明哪些財產是做什麼的,什麼是該財產,如果任何默認。也許通過與@Value註解像上面屬性的註釋:

person.age, default 21: Used to set the age. 

我不是綁定到輸出或任何其他的格式:在東西等導致

/** 
* Used to set the age. 
*/ 
@Value("${person.age:21}") 
private int age; 

。我唯一想要的是爲我的屬性提供某種文檔。如果可能的話,最好的辦法是直接寫入java代碼。

我四處搜索,但到目前爲止找不到任何有用的東西。我發現的唯一事情是使用註釋處理器(http://docs.spring.io/spring-boot/docs/current/reference/html/configuration-metadata.html)生成我自己的元數據。 但我不確定這是否可行。如果是這樣,我會懷疑是否沒有「開箱即用」的解決方案來解決這類問題。我無法想象我是唯一一個想要爲彈簧屬性提供某種文檔的人。

非常感謝您的任何提示。

回答

0

從安德烈亞斯的提示後,我來到了以下解決方案。

我做了一個新的配置類與@ConfigurationProperties註釋持有的屬性年齡

@ConfigurationProperties(prefix = "person") 
public class PersonProperties { 

    /** 
    * Configures the age of person. 
    */ 
    private int age = 18; 

    private int getAge(){ return age; } 
    private int setAge(int age){ this.age = age; } 
} 

我自動裝配這個PersonProperties我以前直接通過訪問屬性的類中@價值(「$ {person.age}」)。在上面的例子中,它將是:

public class Person { 
    @Autowire 
    private PersonProperties properties; 

    public Person(){} 

    private int getAge(){ return properties.getAge; } 
} 

要獲取該屬性的文檔,我只需激活註釋處理。

對於IntelliJ IDEA的: 去設置 - >構建,執行,部署 - >編譯 - >標註處理和標記啓用註釋處理。對於其餘設置,我選擇了默認值。

運行構建後,結果(JSON)將位於項目文件夾。\ target \ classes \ META-INF \ spring-configuration-metadata.json

這是文檔我:

{ 
    "groups": [ 
    { 
     "name": "person", 
     "type": "com.test.PersonProperties", 
     "sourceType": "com.test.PersonProperties" 
    } 
    ], 
    "properties": [ 
    { 
     "name": "person.age", 
     "type": "java.lang.Integer", 
     "description": "Configures the age of person.", 
     "sourceType": "com.test.PersonProperties", 
     "defaultValue": 18 
    } 
    ], 
    "hints": [] 
} 

有了這個解決方案,我仍然可以設置該屬性

something.person.age=25 

application.properties在我的應用程序的文件同時有我的財產記錄。

現在我正在尋找解決方案,讓這種文檔以某種方式好看(也許只是通過簡單的JSON腳本和CSS),並獲得此文檔與validation annotations一起使用。 但這些是不同的問題。

感謝Andreas這個偉大的提示。

0

Spring引導使用PropertyPlaceholderHelper類來旋轉所有屬性。展望該類(here)的源代碼,它使用logger如果啓用跟蹤記錄所有的加工性能,例如:

if (logger.isTraceEnabled()) { 
    logger.trace("Resolved placeholder '" + placeholder + "'"); 
} 

如果添加以下屬性,以春天的application.properties文件,

logging.level.org.springframework.util.PropertyPlaceholderHelper=TRACE

它將啓用該類的跟蹤日誌記錄,您將能夠看到屬性名稱。但是,這不會顯示值,要獲取值,您可以嘗試延長PropertySourcesPlaceholderConfigurer類(可能覆蓋processProperties方法)。

4

如果您使用@ConfigurationProperties beans來管理您的屬性,而不是直接使用@Value來拉動它們,那麼您可以爲這些類編寫javadoc並製作屬性文件文檔。