This section dives into the Coherence Spring Boot module. It explains how to use Coherence’s dedicated support for Spring Boot, e.g., Autoconfiguration.

1. Getting Started

In order to start using Coherence with Spring Boot you have to add the coherence-spring-boot-starter dependency as well as the desired version of Coherence.

Example 1. Adding the Coherence Spring Boot Starter Dependency
Maven
<dependencies>
    <dependency>
        <groupId>com.oracle.coherence.spring</groupId>
        <artifactId>coherence-spring-boot-starter</artifactId>
        <version>3.0.0-M2</version>
    </dependency>
    <dependency>
        <groupId>com.oracle.coherence.ce</groupId>
        <artifactId>coherence</artifactId>
        <version>21.06</version>
    </dependency>
</dependencies>
Gradle
dependencies {
    compile("com.oracle.coherence.spring:coherence-spring-boot-starter:3.0.0-M2")
    compile("com.oracle.coherence.ce:coherence:21.06")
}
As Coherence Spring takes advantage of the new Coherence Bootstrap API, it requires Oracle Coherence CE version 20.12 or higher.

2. Using Coherence with Spring Boot

By adding the coherence-spring-boot-starter dependency, AutoConfiguration will be activated via the CoherenceAutoConfiguration class. This will also bind the CoherenceProperties class for further configuration. The YAML configuration for Spring Boot’s Coherence support may look like the following:

coherence:
  logging:
    destination: slf4j
    logger-name: MyCoherence
  sessions:
  - name: default
    config: "coherence-cache-config.xml"
    priority: 1
  - name: test
    config: "test-coherence-config.xml"
    priority: 2
  properties:
    coherence.log.limit: 400
    coherence.log.level: 1

The following configuration properties are available.

Table 1. Coherence Configuration Properties
Key Default Value Description

coherence.logging.destination

slf4j

The type of the logging destination.

coherence.logging.severity-level

Specifies which logged messages are emitted to the log destination. The legal values are -1 to 9. No messages are emitted if -1 is specified. More log messages are emitted as the log level is increased.

coherence.logging.logger-name

Coherence

Specifies a logger name within chosen logging system

coherence.logging.message-format

Specifies how messages that have a logging level specified are formatted before passing them to the log destination.

coherence.logging.character-limit

Specifies the maximum number of characters that the logger daemon processes from the message queue before discarding all remaining messages in the queue

coherence.sessions.<type>

N/A

Indicates the type of the session. One of the following: grpc, server, client

coherence.sessions.<type>[0].name

Name of the session.

coherence.sessions.<type>[0].config

The Coherence cache configuration URI for the session

coherence.sessions.<type>[0].priority

SessionConfiguration#DEFAULT_PRIORITY

The priority order to be used when starting the session. Sessions will be started with the lowest priority first.

coherence.sessions.<type>[0].scope-name

The scope name for the session.

Session-related configuration properties are defined based on the session type in:

All but the Session properties are translated into native Coherence properties. If both Spring Boot property AND a native property coherence.properties.* are configured, the Spring Boot property is used.

If the provided Spring Boot configuration properties are not sufficient for your needs, you can also specify any of the native Coherence properties. For a list of available native properties, please consult the reference guide chapter on System Property Overrides.

3. Coherence Support of the Spring Boot ConfigData API

Since Spring Boot 2.4.x, you can define your own custom config locations. This allows you to import these config locations as property sources. As such, Coherence Spring allows you to use a Coherence cluster as a source of configuration data for your Spring Boot based applications.

Please also consult the Spring Boot reference guide on Externalized Configuration, especially the chapter on Importing Additional Data.
Please also see the chapter on Coherence Spring Cloud Config.

You can trigger the import of remote configuration properties with the Spring Boot property spring.config.import using the value coherence:. You will also need the corresponding Coherence config-client configured to specify any remote connection settings for your Coherence cluster as well as settings specifying how properties will be applied, e.g., the name of the application used to fetch remote properties.

spring:
  config:
    import: "coherence:"
coherence:
  config-client:
    application-name: berlin
    profile: kona

Many properties have sensible default value. Please see class CoherenceConfigClientProperties for details.

4. Caching with Spring Boot

If you have not already done so, please read the chapter Configuring Coherence Cache for Spring first.

In this chapter, we see how we can use caching with Coherence in Spring Boot. As long as coherence-spring-boot-starter is added to your project, and caching is enabled via @EnableCaching, Coherence Autoconfiguration will automatically provide a CoherenceCacheManager (implementing Spring’s CacheManager) to the ApplicationContext. However, the CacheManager is only added if no CacheManager was configured explicitly beforehand.

Once that is in place, you can take advantage of Spring’s Cache abstraction backed by Coherence and use Spring’s annotations such as @Cacheable, @CacheEvict, @CachePut etc.

When learning about Coherence’s Spring cache abstraction support, please familiarize yourself with the following resources:

5. Configure Hibernate Second-Level Caching

Spring’s cache abstraction is not your only option with regard to caching. Another option is to use Hibernate’s Second-Level cache support.

Currently, Coherence only supports Hibernate up to 5.2.x, as the Hibernate Cache SPI changed with Hibernate 5.3.x and higher. Please track the relevant GitHub issue for the Coherence Hibernate project.

When using only Hibernate’s second-level cache without the requirement of using Coherence for non-Hibernate application needs, you may want to disable Coherence’s auto-configuration support for Spring Boot as it is not needed:

Disable CoherenceAutoConfiguration
@SpringBootApplication(exclude=CoherenceAutoConfiguration.class)
public class HibernateApplication {
    public static void main(String[] args) {
        SpringApplication.run(HibernateApplication.class, args);
    }
}

In order to configure Hibernate Second-Level Caching for Coherence using Spring Boot, you simply have to set the Hibernate property hibernate.cache.region.factory_class to com.oracle.coherence.hibernate.cache.CoherenceRegionFactory.

Your Spring Boot application.yaml file may look like the following:

RegionFactory Configuration using YAML
spring:
  application:
    name: Your Spring Boot App
  jpa:
    properties:
      hibernate.cache.region.factory_class: com.oracle.coherence.hibernate.cache.CoherenceRegionFactory (1)
      hibernate.cache.use_query_cache: true
      hibernate.cache.use_second_level_cache: true
      hibernate.format_sql: true
      hibernate.generate_statistics: true
      hibernate.show_sql: true
      hibernate.use_sql_comments: false
...
1 Configuring the CoherenceRegionFactory

For more detailed information please see the Caching chapter of the Hibernate reference documentation.

5.1. Hibernate Second Level Cache Example

The Coherence Spring source code repository also provides an example application, illustrating the Coherence support for Hibernate’s Second Level caching using Spring Boot.

The example application has 1 REST endpoint that can persist, retrieve and delete a Plant object with taxonomic properties such as the genus and species.

Example of a Plant JSON response
 {"id": 1, "genus": "Sabal", "species": "minor", "commonName": "Dwarf palmetto"}

5.1.1. Run the Hibernate Application

First, let’s build the application:

Build the Coherence Server instance
 $ ./mvnw clean package -pl samples/hibernate-cache-demo

Next, run the application:

Run the Spring Boot application
 $ java -jar samples/hibernate-cache-demo/target/hibernate-cache-demo-3.0.0-M2.jar

The application will be available on port 9090.

Add a plant
curl -i \
  -H "Accept: application/json" \
  -H "Content-Type:application/json" \
  -X POST --data '{"genus": "Sabal", "species": "minor", "commonName": "Dwarf palmetto"}' \
  "http://localhost:9090/plants"
List all plants
curl -i \
  -H "Accept: application/json" \
  -H "Content-Type:application/json" \
  -X GET "http://localhost:9090/plants"
Get a single plant
curl -i \
  -H "Accept: application/json" \
  -H "Content-Type:application/json" \
  -X GET "http://localhost:9090/plants/1"
Delete a plant
curl -i \
  -H "Accept: application/json" \
  -H "Content-Type:application/json" \
  -X DELETE "http://localhost:9090/plants/1"

When retrieving a single plant repeatedly, you will see no SQL printed to the console. Instead, the plant is returned from the second level cache as illustrated by the printed out cache statistics.

Hibernate Cache Statistics
2021-06-28 16:12:42.545  INFO 29022 --- [nio-9090-exec-7] i.StatisticalLoggingSessionEventListener : Session Metrics {
27579 nanoseconds spent acquiring 1 JDBC connections;
0 nanoseconds spent releasing 0 JDBC connections;
0 nanoseconds spent preparing 0 JDBC statements;
0 nanoseconds spent executing 0 JDBC statements;
0 nanoseconds spent executing 0 JDBC batches;
0 nanoseconds spent performing 0 L2C puts;
1587296 nanoseconds spent performing 1 L2C hits;
0 nanoseconds spent performing 0 L2C misses;
0 nanoseconds spent executing 0 flushes (flushing a total of 0 entities and 0 collections);
0 nanoseconds spent executing 0 partial-flushes (flushing a total of 0 entities and 0 collections)
}

In order to also cache the results of query executions, you must provide query hints to Hibernate. The PlantRepository class has a custom query using such a hint for illustration purposes:

Using Query Hints
@QueryHints(@QueryHint(name = org.hibernate.annotations.QueryHints.CACHEABLE, value = "true"))
@Query("select p from Plant p")
List<Plant> getAllPlantsCacheable();

You can see the cache being used by retrieving the list of plants with an additional request parameter use-cache:

List all plants
curl -i \
  -H "Accept: application/json" \
  -H "Content-Type:application/json" \
  -X GET "http://localhost:9090/plants?use-cache=true"

6. Spring Session Support

If you have not already done so, please read the chapter on Coherence Spring Session first.

Coherence Spring also provides support for Spring Session. This includes auto-configuration support as well as a set of Coherence-specific configuration properties.

The following Coherence-specific configuration properties are available:

Table 2. Coherence Configuration Properties
Key Default Value Description

coherence.spring.session.enabled

false

Set to true to enable Spring Session support

coherence.spring.session.map-name

spring:session:sessions

Name of the map used to store sessions

coherence.spring.session.flush-mode

ON_SAVE

Sessions flush mode. Determines when session changes are written to the session store.

coherence.spring.session.save-mode

ON_SET_ATTRIBUTE

The session save mode determines how session changes are tracked and saved to the session store.

7. Coherence Messaging Support

Support for injecting Coherence Publishers is enabled automatically by adding the coherence-spring-boot-starter dependency. By default, base package to scan for @CoherencePublisher annotated interfaces is derived from the main class annotated with @SpringBootApplication. Base package can be overridden by annotating configuration class with @CoherencePublisherScan as described at Messaging with Coherence Topics.

8. Coherence Metrics

By adding the coherence-spring-boot-starter and com.oracle.coherence.ce:coherence-micrometer dependencies auto-configuration will register CoherenceMicrometerMetrics and publish Coherence Metrics under the coherence. name.

To disable the auto-configured Coherence metrics even when coherence-micrometer module is on the classpath, set the following property:

application.yaml
management:
  metrics:
    enable:
      coherence: false