jakarta-ee - Spring @Profile 的 EJB 对应物
问题描述
Spring Profiles 提供了一种分离应用程序配置部分并使其仅在某些环境中可用的方法。想知道这是否也可以在 EJB 中以任何方式完成?
主要问题陈述:
我在两个不同的环境中有两个不同的 JMS 基础架构。我希望加载和注入相应的bean。
解决方案
您可以使用 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)中,并在为该环境创建的每个环境中使用正确的一个(为每个环境进行适当的组装)
推荐阅读
- java - 如何使用 Firebase 身份验证 android studio 使用电子邮件和密码进行注册
- npm - 找不到模块:无法解析 gatsby 健全项目中的“@react-icons/all-files”
- node.js - 我尝试在本地计算机上全局安装 ionicons,但出现以下错误
- ios - 打开通用链接不会在应用程序中打开
- selenium - 即使 system.set 属性文件中的键和值正确,我也无法启动 Chrome 浏览器
- arrays - 如何在每行中显示两列是Scrollview而不是Flatlist?反应原生
- node.js - 无效响应和空 API 响应 - Alexa 对话问题
- python - 如何在openCV中获取带有视频输入的屏幕大小?
- python - TypeError:“dict”和“int”的实例之间不支持“>”
- python - 您可以将列表存储到while循环内的列表中吗?