Spring Profiles 提供了一种隔离应用程序配置的各个部分并使其仅在某些环境中可用的方法。想知道这是否也可以在 EJB 中以任何方式完成?
主要问题陈述:
我在两个不同的环境中有两个不同的 JMS 基础设施。我想要加载并注入(inject)相应的bean。
最佳答案
您可以使用 CDI 替代方案并使用 @Inject 而不是 @EJB 进行注入(inject) 例子: 1)如果您需要在部署时指定实现,您可以使用替代方案
界面:
import javax.ejb.Local;
@Local
public interface MyserviceInterface2 {
String doSomthing();
}
实现
@Alternative
@Stateless
public class Interface2Impl1 implements MyserviceInterface2{
@Override
public String doSomthing() {
return "Impl1";
}
}
@Alternative
@Stateless
public class Interface2Impl2 implements MyserviceInterface2{
@Override
public String doSomthing() {
return "Impl2";
}
}
在 beans.xml 中选择您的实现
<alternatives>
<class> [your package].Interface2Impl1</class>
</alternatives>
注入(inject)点:
inject in client class
public class ClientClass {
@Inject
MyserviceInterface2 myserviceInterface2;
...
2)如果你想在运行时选择实现,你可以使用 Produce
创建以下限定符
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD})
public @interface Impl1Qulifier {
}
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD})
public @interface Impl2Qulifier {
}
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD})
public @interface SelectedImpQulifier {
}
界面:
@Local
public interface MyServiceInterface {
String doSomthing();
}
实现:
@Impl1Qulifier
@Stateless
public class MyServiceImpl1 implements MyServiceInterface{
@Override
public String doSomthing() {
return "Impl1";
}
}
@Impl2Qulifier
@Stateless
public class MyServiceImpl2 implements MyServiceInterface{
@Override
public String doSomthing() {
return "impl2";
}
}
产生:
public class ImplProvider {
@Inject @Impl1Qulifier
MyServiceInterface impl1;
@Inject @Impl2Qulifier
MyServiceInterface imp2;
@Produces @SelectedImpQulifier
MyServiceInterface createServiceInterface(InjectionPoint injectionPoint ) {
// if( your conditions ){
// return impl1
// }
return imp2;
}
}
注入(inject)点:
public class ClientClass {
@Inject @SelectedImpQulifier
MyServiceInterface myServiceInterface;
...
对于第二种情况,您还可以使用 JNDI 查找
您还可以将每个实现放在不同的模块(jar)中,并为 Ear 中为该环境创建的每个环境使用正确的模块(为每个环境进行正确的组装)
关于jakarta-ee - Spring @Profile 的 EJB 对应项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52522891/