Skip to content
Mike Kistler edited this page Feb 5, 2018 · 1 revision

We have added Spring Boot support for the Watson services.

This means that you can now "auto-wire" any of the Watson services into your Spring Boot application using the standard Spring autoconfiguration framework.

All you need to do is:

  1. Add the Watson spring-boot-starter dependency to your Spring Boot app:

    In your maven pom.xml

    <dependency>
      <groupId>com.ibm.watson.developer_cloud</groupId>
      <artifactId>watson-spring-boot-starter</artifactId>
      <version>0.0.2</version>
    </dependency>
    

    or in your gradle build.gradle, in the dependencies stanza, add

    compile 'com.ibm.watson.developer_cloud:spring-boot-starter:0.0.2'
    
  2. Add your Watson service(s) credentials and version info to your application properties file. The standard location for application properties is the src/main/resources/application.properties file, but your application might use a different location. The properties to add are:

  • watson.<service>.url: The base URL for the service. This can be omitted if your service uses the default service url

  • watson.<service>.username and watson.<service>.password OR watson.<service>.apiKey: The credentials for accessing the service. The credentials can be omitted from the application properties file if they are supplied through the VCAP_SERVICES environment variable.

  • watson.<service>.versionDate: Some Watson services use a versionDate parameter to indicate the service behavior expected by the application. For services that accept it, this is a required parameter and must be specified in the application properties.

    Both Eclipse and IntelliJ (Ultimate Edition) offer autocomplete support for Spring Boot application properties and should show these properties, along with their required type and Javadoc description, in the autocomplete menu.

  1. Autowire the service into your application. Autowiring is the key mechanism of the Spring framework for injecting dependencies. It is accomplished by specifying the @Autowired annotation on the declaration for the service instance. Here's an example using the Watson Conversation service:
@Autowired
protected Conversation service;

The Spring framework takes care of the rest. Your application can now simply start using the service instance.

An Example

To demonstrate how this works, let's create a simple Spring Boot Application and then add a Watson service into it using the steps above.

We'll use the Spring Boot Initializr to create the base application. You can choose either a maven or gradle project. Using the simple interface, we'll choose:

  • Generate a gradle project,
  • artifact name watson-spring-demo, and
  • dependencies Web.

Then we click generate to download the project zip and unzip it into our projects directory.

unzip ~/Downloads/watson-spring-demo.zip

Open the code in your favorite IDE -- I'll use IntelliJ -- to see what we have.

We'll add a simple REST endpoint to give us a place to hook in our Watson support. For that we add the @RestController annotation to our main class, and add a method, annotated with @GetMapping, to handle the request.

@GetMapping("/endpoint")
String endpoint() {
    return "Hello from my REST endpoint\n";
}

Now we could run this and hit this endpoint, and it would respond with string shown. But let's keep going and integrate our Watson service.

Following the steps above, let's integrate the IBM Watson™ Discovery Service service into our application. The Discovery Service is a cognitive search and content analytics engine that supports natural language queries of structured and unstructured data.

First we add the dependency into our build.gradle.

compile 'com.ibm.watson.developer_cloud:spring-boot-starter:0.0.2'

(Until watson-spring-boot is officially published in Maven Central, you have to build it locally and add mavenLocal() to the repositories section of build.gradle.)

Next we open up the src/main/resources/application.properties file, which is initially empty, and add the properties for our instance of the Discovery service. You can easily create an "Lite" (free) instance of Discovery from the IBM Cloud console.

You can get the credentials for your instance of Discovery from the IBM Cloud console by navigating to the service and selecting "Credentials" from the left pane. If no credentials are listed, click the "New Credential" button to create a set of credentials. Then click on the "view credentials" twistie to reveal the service credentials.

watson.discovery.url=https://gateway.watsonplatform.net/discovery/api
watson.discovery.username=<Discovery username>
watson.discovery.password=<Discovery password>
watson.discovery.versionDate=2017-12-28

Finally, we add an autowired instance of the Discovery service to our app.

@Autowired
protected Discovery discovery;

Now Spring will instantiate and inject an instance of the Discovery client into our application that we can simply use. Here we'll just do something simple to demonstrate that our Discovery instance is indeed live and ready to be used. We'll use the built-in Watson Discovery News collection, a dataset of English language news sources that is updated continuously, with approximately 300,000 new articles and blogs added daily.

String endpoint(@RequestParam String query) {

  QueryOptions options = new QueryOptions.Builder("system", "news")
      .naturalLanguageQuery(query)
      .build();
  QueryResponse queryResponse = discovery.query(options).execute();

  String titles = queryResponse.getResults().stream()
      .map(r -> (String) r.get("title"))
      .collect(Collectors.joining("\n<p>"));

  return titles;
}

This code takes a query string from the request and uses it as the natural language query against our Watson Discovery News collection. The response contains a list of results (10 by default) for recent news articles that match the query string. Here we simply extract the title of each of these articles and return these in the response.

To see this in action, start the app (from within your IDE, or from the command line with gradle bootRun), and then make a request to the application like the following:

http://localhost:8080/endpoint?query=IBM+Cloud

This should display a simple text list of the titles for the first 10 articles matching your query.

Thats it!

Clone this wiki locally