2016-09-22 38 views
1

我是而不是在我的應用程序中使用Spring。是否有任何API可以根據註釋將屬性文件加載到java pojo中。 我知道使用InputStream或Spring的PropertyPlaceHolder加載屬性文件。 是否有使用,我可以填充我的POJO喜歡以註解的方式讀取沒有Spring的屬性文件的任何API

@Value("{foo.somevar}") 
private String someVariable; 

我無法用彈簧找到任何解決方案任何API。

+0

'.properties'文件?你嘗試過'ResourceBundle'嗎?儘管如此,它不會像你所嘗試的那樣工作。 – GustavoCinque

+0

你可以自己寫。使用反射API。 –

+0

@MdFaraz是的,這就是我現在正在做的事情,但是如果有一個API得到了充分證明,那麼它的價值使用將會更好地通過功能進行測試。 – Sankalp

回答

2

我想出了一個快速入侵方法來綁定屬性,如下所示。

注意:它沒有優化,沒有錯誤處理。只是展示一種可能性。

@Retention(RetentionPolicy.RUNTIME) 
@interface Bind 
{ 
    String value(); 
} 

我測試了一些基本參數並且正在工作。

class App 
{ 
    @Bind("msg10") 
    private String msg1; 
    @Bind("msg11") 
    private String msg2; 

    //setters & getters 
} 

public class PropertyBinder 
{ 

    public static void main(String[] args) throws IOException, IllegalAccessException 
    { 
     Properties props = new Properties(); 
     InputStream stream = PropertyBinder.class.getResourceAsStream("/app.properties"); 
     props.load(stream); 
     System.out.println(props); 
     App app = new App(); 
     bindProperties(props, app); 

     System.out.println("Msg1="+app.getMsg1()); 
     System.out.println("Msg2="+app.getMsg2()); 

    } 

    static void bindProperties(Properties props, Object object) throws IllegalAccessException 
    { 
     for(Field field : object.getClass().getDeclaredFields()) 
     { 
      if (field.isAnnotationPresent(Bind.class)) 
      { 
       Bind bind = field.getAnnotation(Bind.class); 
       String value = bind.value(); 
       String propValue = props.getProperty(value); 
       System.out.println(field.getName()+":"+value+":"+propValue); 
       field.setAccessible(true); 
       field.set(object, propValue); 
      } 
     } 
    } 
} 

在根類路徑中創建app.properties

msg10=message1 
msg11=message2 
相關問題