繁体   English   中英

EJB 在运行时更新 bean 属性

[英]EJB update bean property at runtime

我有一个包含一些 web 客户端实现的 bean,它可以是 REST 或 SOAP:

@Stateless
public class Service{
  private Client client;

  @PostConstruct
  public void init() {
    this.client = new RESTClient();
  }
}

有没有办法可以更新“客户端”,例如在 JSF controller 中,并且此更改在整个应用程序的上下文中持续存在?

@ViewScoped
@ManagedBean
public class ServiceController {

  @EJB
  private Service service;

  public void updateClient() {
     // code to update the client
     // Service.client = new SOAPClient();
  }
}

根据您的评论,如果您的堆栈中有 CDI,我建议您使用它。

CDI 具有许多功能,您可以使用这些功能来准确地完成您想要做的事情:Alternative 似乎最适合您的用例,但您还应该检查 Qualifiers、Decorators 和 Specializes/Stereotypes。

这里有一个参考: https://docs.jboss.org/weld/reference/latest/en-US/html/specialization.html

@RequestScoped
public class RESTClient
      implements Service {
   ...
}

@Alternative @RequestScoped
public class SoapClient
      implements Service {
   ...
}

@ViewScoped
@ManagedBean
public class ServiceController {
   @Inject private Service service;
}

然后,您可以在运行时在 beans.xml 中交换活动替代项:

<beans
   xmlns="http://xmlns.jcp.org/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="
      http://xmlns.jcp.org/xml/ns/javaee
      http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd">
   <alternatives>
         <class>org.mycompany.myapp.SoapClient</class>
   </alternatives>
</beans>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM