12

依存性注入を宣言する Spring DI applicationContext.xml の方法を経験したので、Java EE6 CDI で同じことを行う方法を理解しようとしています。

Spring を使用すると、unittest.xml、devel.xml、qa.xml、production.xmlなどのいくつかの構成プロファイルを含む .jar を出荷 し、コマンド ライン パラメーターまたは環境変数を使用してそれらをアクティブ化できます。

CDI を使用すると、 beans.xmlで@Alternative を使用し、 web.xmlのプロパティを使用できますが、異なる環境に複数の beans.xml を出荷する方法はないようです。

Maven プロファイル/フィルターを使用してアプリの 4 ~ 6 バージョンを生成したくありませんが、いくつかのシナリオではそれがより良い解決策になることを理解しています (つまり、準備完了のビルド戦争を顧客に出荷します - しかし、私は自分の戦争を内部でのみ使用するため、コンパイル時間を節約しましょう!)

できれば、これらの構成ファイルをファイル システムから読み込んで、システム管理者がアプリを再ビルドしなくても編集できるようにすることもできます。

依存関係とプロパティの複数の構成セットを持つJava EE6の方法は何ですか?

何もない場合、2013 年時点で推奨される代替手段は何ですか? 春を使用していますか?縫い目?ギース?Apache DeltaSpike についての言及を見ましたが、Web ページから判断するとまだアルファ版のようです。

4

3 に答える 3

12

を使用して動的プロデューサーを使用しQualifier、目的の環境を識別します

// The qualifier for the production/qa/unit test 
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD,
 ElementType.FIELD, ElementType.PARAMETER})
public @interface Stage {
   String value() default "production";
}

// The interface for the stage-dependant service
public interface Greeting{
    public String sayHello();
}

// The production service
@Stage("production")
public class ProductionGreeting implements Greeting{
    public String sayHello(){return "Hello customer"; }
}

// The QA service
@Stage("qa")
public class QAGreeting implements Greeting{
    public String sayHello(){return "Hello tester"; }
}

// The common code wich uses the service
@Stateless
public class Salutation{
   @Inject Greeting greeting; 
   public String sayHello(){ return greeting.sayHello(); };
}

// The dynamic producer
public class GreetingFactory{
    @Inject
    @Any
    Instance<Greeting> greetings;        

    public String getEnvironment(){
         return System.getProperty("deployenv");
    }

    @Produces
    public Greeting getGreeting(){
        Instance<Greeting> found=greetings.select(
           new StageQualifier(getEnvironment()));
        if (!found.isUnsatisfied() && !found.isAmbiguous()){
           return found.get();
        }
        throw new RuntimeException("Error ...");
    }

    public static class StageQualifier 
      extends AnnotationLiteral<Stage> 
      implements Stage {
       private String value;

       public StageQualifier(String value){
           this.value=value;
       }
       public String value() { return value; }
     }

}

したがって、ここでコンテナは利用可能なすべてのGreeting実装を に注入します。これは、システム プロパティ「deployenv」に基づく決定に基づいて、意図したものGreetingFactoryとして機能します。@Producer

于 2013-06-04T15:00:24.877 に答える
2

カルロによる上記の回答は良いです。これはすべて DeltaSpikeと ProjectStage にあります。自分ですべてを書く必要がないので、見てみる価値があります。

于 2013-06-04T15:39:58.510 に答える