Now that we have the interface and response exception mapper written, we just need to build the implementation and then invoke it. There are two ways to build the implementation: using the RestClientBuilder API or using CDI and MicroProfile Config. We’ll start with the RestClientBuilder - it is a little more verbose but can come in handy in environments where CDI is not available, like testing.

First we create a new instance of the RestClientBuilder . We must specify the baseUrl value for the remote endpoint - this is required before building the client. Next, we register the response exception mapper. If we need to register other provider classes like MessageBodyReaders or MessageBodyWriters , filters, interceptors, etc., we would do that here with the register method. Then we build the client, passing in the interface class. After that we can invoke methods on the client like it was any other Java object.

CDI and MicroProfile Config integration

It is also possible to let CDI instantiate the client. For all of the code we have covered so far, the user only needs to install the mpRestClient-1.0 feature in the Liberty server.xml . In order for this CDI approach to operate, we need to add two more features: cdi-1.2 (or 2.0) and mpConfig-1.1 (or 1.2). First, we need to update the MusicPlaylistService with some new annotations:

@Path ( " /playlist " ) @Consumes ( " application/json " ) @Dependent @RegisterRestClient @RegisterProvider (PlaylistResponseExceptionMapper.class) public interface MusicPlaylistService { ...

The @Dependent and @RegisterRestClient annotations declare that this interface is to be managed by CDI. The @RegisterProvider annotation tells the MicroProfile Rest Client implementation code to register the specified provider class. This annotation can be repeated for as many providers as necessary. Now we can inject the client in another managed object like this:

@WebServlet (urlPatterns = " /PlaylistServlet " ) public class PlaylistServlet extends HttpServlet { @Inject @RestClient private MusicPlaylistService playlistService; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List < String > names = playlistService.getPlaylistNames(); ... }

The @Inject combined with the @RestClient decorator tells CDI that we want to inject an instance of the MusicPlaylistService interface. There is still one more step…​ we need to tell the MicroProfile Rest Client implementation the baseUrl value for the remote endpoint. For that, we use MicroProfile Config. The config property to use is <fullyQualifiedInterfaceName>/mp-rest/url . So you could specify this as a system property in the jvm.options file like this:

-Dcom.mypkg.MusicPlaylistService/mp-rest/url=http://localhost:9080/onlineMusicService