拥有使用 Spring DI applicationContext.xml 声明依赖注入的方式的经验后,我现在尝试弄清楚如何使用 Java EE6 CDI 执行相同的操作。
使用 Spring,我可以将我的 .jar 与多个配置文件一起发送,例如unittest.xml、devel.xml、qa.xml、生产.xml并使用命令行参数或环境变量激活它们。
通过 CDI,我可以在中使用 @Alternativebeans.xml和属性在web.xml但似乎没有办法为不同的环境传送多个 beans.xml 。
我不想使用 Maven 配置文件/过滤器来生成我的应用程序的 4-6 个版本,尽管我知道对于某些场景来说,这将是更好的解决方案(即将准备好的构建战争交付给客户 - 但我只在内部使用我的战争,所以让我们节省编译时间!)
最好,我还能够从文件系统加载这些配置文件,以便系统管理员可以编辑它们,而无需重新构建应用程序。
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
实施到GreetingFactory
,这反过来又充当@Producer
对于预期的,根据系统属性“deployenv”做出决定。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)