首页 > 解决方案 > Spring @Profile 的 EJB 对应物

问题描述

Spring Profiles 提供了一种分离应用程序配置部分并使其仅在某些环境中可用的方法。想知道这是否也可以在 EJB 中以任何方式完成?

主要问题陈述:

我在两个不同的环境中有两个不同的 JMS 基础架构。我希望加载和注入相应的bean。

标签: jakarta-eeejb

解决方案


您可以使用 CDI 替代方案并使用 @Inject 而不是 @EJB 进行注入示例: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 in client class

public class ClientClass {
    @Inject
    MyserviceInterface2 myserviceInterface2;
    ...

2)如果你想在运行时选择实现,你可以使用生产

创建以下 qualfires

@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;
    }
}

注入点:

public class ClientClass {
    @Inject @SelectedImpQulifier
    MyServiceInterface myServiceInterface;
    ...

你也可以使用 JNDI 查找第二种情况

您还可以将每个实现放在不同的模块(jar)中,并在为该环境创建的每个环境中使用正确的一个(为每个环境进行适当的组装)


推荐阅读