2016-09-22 4 views
1

私はではない私のアプリケーションでは春を使用しています。アノテーションに基づいてプロパティファイルをJava pojoにロードできるAPIはありますか? 私は、InputStreamまたはSpringのPropertyPlaceHolderを使用してプロパティファイルを読み込むことに気付いています。 注釈の方法でSpringなしでプロパティファイルを読み込むAPI

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

私は春を使用してなしソリューションを見つけることができませんでしたように私は私のPOJOを移入することができた使用して、任意のAPIがあります。

+0

'.properties'ファイルですか? 'ResourceBundle'を試しましたか?しかし、あなたが試しているように動作しません。 – GustavoCinque

+0

あなた自身で書くことができます。リフレクションAPIの使用。 –

+0

@MdFarazはい、それは私が今やっていることですが、APIが十分に実証されていれば、その価値ある使い方は機能でよりよくテストされます。 – Sankalp

答えて

2

次のように、プロパティをバインドするための簡単なハックを思いつきます。

注:最適化されておらず、エラー処理されていません。ただ一つの可能​​性を示しています。

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

私はそれをいくつかの基本的なのparamsをテストしているし、取り組んでいます。

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 
関連する問題