1

I have a bean that contains some web client implementation that can be REST or SOAP:

@Stateless
public class Service{
  private Client client;

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

Is there a way that I can update the "client", for example in a JSF controller and this change persists in the context of the entire application?

@ViewScoped
@ManagedBean
public class ServiceController {

  @EJB
  private Service service;

  public void updateClient() {
     // code to update the client
     // Service.client = new SOAPClient();
  }
}
bxacosta
  • 49
  • 1
  • 5

1 Answers1

1

Per your comment, I would suggest using CDI if you have it available in your stack.

CDI has a number of features you could use to accomplish exactly what you're trying to do: Alternative seems to maybe best fit your use case, but you should also examine Qualifiers, Decorators, and Specializes/Stereotypes.

Here is a reference: 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;
}

You can then swap the active alternative at Runtime in your 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>
Jonathan S. Fisher
  • 8,189
  • 6
  • 46
  • 84