gpt4 book ai didi

java - 一场 war 中的多个 CDI 配置文件(开发、测试、质量保证、生产)?

转载 作者:IT老高 更新时间:2023-10-28 13:49:07 27 4
gpt4 key购买 nike

拥有使用 Spring DI applicationContext.xml 声明依赖注入(inject)方式的经验,我现在尝试弄清楚如何对 Java EE6 CDI 做同样的事情。

使用 Spring,我可以将我的 .jar 与多个配置文件一起发布,例如unittest.xml、devel.xml、qa.xml、production.xml并使用命令行参数或环境变量激活它们。

使用 CDI,我可以在 beans.xml 中使用 @Alternative 并在 web.xml 中使用属性,但似乎无法为不同的环境提供多个 beans.xml .

我不想使用 Maven 配置文件/过滤器来生成我的应用程序的 4-6 个版本,尽管我知道在某些情况下这将是更好的解决方案(即向客户发送准备好的构建 war - 但我只使用我的内部 war ,所以让我们节省编译时间!)

最好,我还可以从文件系统加载这些配置文件,以便系统管理员可以编辑它们而无需重新构建应用程序。

Java EE6 拥有多个依赖项和属性的配置集的方式是什么?

如果没有,截至 2013 年推荐的替代方案是什么?使用 Spring ?接缝?古斯?我看到有人提到 Apache DeltaSpike,但从网页上看,它们似乎仍然是 alpha。

最佳答案

我会使用动态生产者,使用 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 实现注入(inject)到 GreetingFactory 中,而 GreetingFactory 又作为预期的 @Producer 实现,基于决定系统属性“deployenv”。

关于java - 一场 war 中的多个 CDI 配置文件(开发、测试、质量保证、生产)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16907185/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com