2011-10-28 16 views
1

私はクライアント/サーバーアプリケーションを作成し、Springで設定しています。実行時に固有の構成メタデータをSpringにどのように提供しますか?

私のクライアントインターフェイスは、サーバーへのマーシャリング要求を処理し、応答を処理します。現時点で

、私のようなものに見えるの工場があります。今

public class ClientFactory { 
    private ApplicationContext ctx; 
    public ClientFactory(){ 
    ctx = new AnnotationConfigApplicationContext(MyConfig.class); 
    } 

    public MyClient(String host, int port){ 
    MyClient client = ... 
    // create a connection to the server 
    return client; 
    } 
} 

を、MyClientという私は注入したい依存関係の束を持っているので、私は春を使用してMyClientというインスタンスを作成したいです@Injectアノテーションを使用して依存関係を挿入します。

構成メタデータとしてホスト/ポートをSpring構成に渡すにはどうすればよいですか。もし私が何ができない場合は、代わりに推奨されます。私はすべての配線を自分で行うことができますが、それがSpringの目的です。

Jeff

答えて

0

スプリングリファレンスの設定部分を確認する必要があります。たとえば、spring 3.xでこのようなBeanを作成することができます。

@Configuration 
// spring config that loads the properties file 
@ImportResource("classpath:/properties-config.xml") 
public class AppConfig { 

    /** 
    * Using property 'EL' syntax to load values from the 
    * jetProperties value 
    */ 
    private @Value("#{jetProperties['jetBean.name']}") String name; 
    private @Value("#{jetProperties['jetBean.price']}") Long price; 
    private @Value("#{jetProperties['jetBean.url']}") URL url; 

    /** 
    * Create a jetBean within the Spring Application Context 
    * @return a bean 
    */ 
    public @Bean(name = "jetBean") 
    JetBean jetBean() { 
     JetBean bean = new JetBeanImpl(); 
     bean.setName(name); 
     bean.setPrice(price); 
     bean.setUrl(url); 
     return bean; 
    } 

} 
+0

はい、ただし、依然として必要なjetProperties定義を含む事前定義プロパティファイルが必要です。私はこれらを実行時に指定したいと思います。おそらく私はこれらの特性をその場で作成することに目を向けることができます。 – user1018319

+0

実行時にBeanが作成されます。これは、これらのsetName、setPriceメソッドをカスタムランタイムロジックで設定できることを意味します。あなたはあらかじめ定義されたプロパティを使用する必要はありません。 – Cemo

0

これを静的構成クラスを使用して解決しました。

public class ClientFactory { 
    private ApplicationContext ctx; 
    public ClientFactory(){ 
    ctx = new AnnotationConfigApplicationContext(MyConfig.class,ServerConfig.class); 
    } 

    public MyClient(String host, int port){ 
    MyClient client = ... 
    // create a connection to the server 
    return client; 
    } 

    @Data 
    @AllArgsConstructor 
    public static class ServerDetails{ 
    private int port; 
    private String host; 
    } 

    @Configuration 
    public static class ServerConfig{ 
    static String host; 
    static int port; 

    @Bean 
    public void serverDetails(){ 
     return new ServerDetails(host, port); 
    } 
    } 
} 

しかし、非常にclunky感じます。より良い方法がありますか?

関連する問題