jakarta-ee - Spring @Profile 的 EJB 对应项

标签 jakarta-ee ejb

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/

相关文章:

java - 条件 API 组合 AND/OR

java - 将外部 JAR 添加到 Openshift

java - 如何挂载Hadoop HDFS

jpa - JTA 事务提交太早,使用约束时失败

java - 如何正确地对 EJB3 和 servlet 进行分层?

java - EJB 和现代 Java 开发

jakarta-ee - WFLYEJB0043 : A previous execution of timer [timer] is still in progress, 在 [时间] 跳过这个重叠的计划执行

jakarta-ee - Swagger 2.x JaxrsAnnotationScanner 找不到位于 ear 中的资源类

glassfish - 禁用 EJB 计时器(GlassFish 3.1、Java EE 6)

java - 本地 EJB 的 JNDI 查找(无 @EJB)