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>5.0.0</version>
    </dependency>
    <dependency>
        <groupId>com.oracle.coherence.ce</groupId>
        <artifactId>coherence</artifactId>
        <version>26.04</version>
    </dependency>
</dependencies>
Gradle
dependencies {
    implementation("com.oracle.coherence.spring:coherence-spring-boot-starter:5.0.0")
    implementation("com.oracle.coherence.ce:coherence:26.04")
}
Under the covers Coherence Spring takes advantage of the Coherence Bootstrap API. For more information, check out the respective chapter on the Bootstrap API in the Coherence reference guide.

2. Auto-configuration

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.

By default, Coherence Spring will start Coherence in clustered mode (Server). If you want to use Coherence in client mode (Coherence*Extend or gRPC), please see the chapter on setting up Spring Boot as a Coherence Client.

When using Coherence Spring Boot, you may want to verify that only the auto-configuration that you actually need is enabled. Spring Boot 4 places feature-specific auto-configuration in dedicated modules. For example, if an application includes the spring-boot-gson module and Gson is present, Boot may activate GsonAutoConfiguration.

To find out which auto-configuration is applied for your application, start your Spring Boot application with the --debug argument. The auto-configuration report will be logged to the console.

Any auto-configuration that you do not want to be applied, can be disabled by specifying the exclude property on the @SpringBootApplication annotation on your main application class. Just specify the name of the auto-configuration classes that you do not want to be applied.

import org.springframework.boot.gson.autoconfigure.GsonAutoConfiguration;

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

Alternatively, you can also disable specific auto-configuration by setting the spring.autoconfigure.exclude property in your application.properties or application.yaml file.

application.yaml
spring:
    autoconfigure:
        exclude: org.springframework.boot.gson.autoconfigure.GsonAutoConfiguration

2.1. Testing without starting Coherence

For mock-based @SpringBootTest tests that do not need a running Coherence instance, exclude Coherence’s core, Spring Session, and Spring Data auto-configurations in the test configuration. Session and Data auto-configuration are registered independently of CoherenceAutoConfiguration and can remain active when their conditions match, even if only the core auto-configuration is excluded. Session configuration requires Coherence-backed sessions, and Data configuration can create Coherence repositories; these are usually unwanted when testing with mock caches.

Use @TestPropertySource to keep the exclusions scoped to the test. Place the following test in your application’s test sources, where @SpringBootTest can discover your @SpringBootApplication class:

import org.junit.jupiter.api.Test;

import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;

@SpringBootTest
@TestPropertySource(properties = {
    "spring.autoconfigure.exclude="
        + "com.oracle.coherence.spring.boot.autoconfigure.CoherenceAutoConfiguration,"
        + "com.oracle.coherence.spring.boot.autoconfigure.session."
        + "CoherenceSpringSessionAutoConfiguration,"
        + "com.oracle.coherence.spring.boot.autoconfigure.data."
        + "CoherenceRepositoriesAutoConfiguration"
})
class MockCacheTests {

    @Test
    void testWithMockCaches() {
        // Add assertions for application behavior using your test's mock caches.
    }
}

The exclusions do not supply mock beans. Configure the mocks needed by your application, including any cache, session, or repository dependencies, separately in the test context.

These exclusions apply to Spring Boot auto-configuration. They do not disable explicit @EnableCoherence imports or other manually configured Coherence startup. Omit or replace that configuration in mock-based tests as well.

If your production @SpringBootApplication class declares @EnableCoherence, select a dedicated test bootstrap with @SpringBootTest(classes = …​). For example, the following application service reads an order’s status from the orders cache through @CoherenceMap:

package com.oracle.coherence.spring.doc.boot.mockcache;

import com.oracle.coherence.spring.configuration.annotation.CoherenceMap;
import com.tangosol.net.NamedCache;

import org.springframework.stereotype.Service;

@Service
public class OrderService {

    private final NamedCache<Long, String> orders;

    public OrderService(@CoherenceMap("orders") NamedCache<Long, String> orders) {
        this.orders = orders;
    }

    public String getStatus(long orderId) {
        return this.orders.get(orderId);
    }

}

Place this test in your test sources and adapt the packages and imported application components as needed. Spring Framework’s @MockitoBean supplies the cache mock to both the test and the service:

package com.oracle.coherence.spring.doc.boot.mockcache.tests;

import com.oracle.coherence.spring.configuration.NamedCacheConfiguration;
import com.oracle.coherence.spring.doc.boot.mockcache.OrderService;
import com.tangosol.net.NamedCache;
import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.bean.override.mockito.MockitoBean;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@SpringBootTest(classes = IsolatedMockCacheTests.TestApplication.class)
@TestPropertySource(properties = {
    "spring.autoconfigure.exclude="
        + "com.oracle.coherence.spring.boot.autoconfigure.CoherenceAutoConfiguration,"
        + "com.oracle.coherence.spring.boot.autoconfigure.session."
        + "CoherenceSpringSessionAutoConfiguration,"
        + "com.oracle.coherence.spring.boot.autoconfigure.data."
        + "CoherenceRepositoriesAutoConfiguration"
})
class IsolatedMockCacheTests {

    @MockitoBean(name = NamedCacheConfiguration.COHERENCE_CACHE_BEAN_NAME)
    NamedCache<Long, String> orders;

    @Autowired
    OrderService orderService;

    @Test
    void readsOrderStatusFromCache() {
        when(this.orders.get(42L)).thenReturn("SHIPPED");

        assertEquals("SHIPPED", this.orderService.getStatus(42L));
        verify(this.orders).get(42L);
    }

    @Configuration(proxyBeanMethods = false)
    @EnableAutoConfiguration
    @Import(OrderService.class)
    static class TestApplication {
    }

}

The explicit mock bean name matters: @CoherenceMap is meta-annotated with @Value resolving #{getCacheProxy}, and NamedCacheConfiguration.COHERENCE_CACHE_BEAN_NAME supplies that bean name. The orders annotation value is the logical cache name used by production cache resolution. A mock registered only by type or named orders does not satisfy this expression. With Coherence configuration excluded, @MockitoBean creates the named bean; leave enforceOverride at its default of false, since there is no production cache bean to replace.

This example uses one cache mock. Every @CoherenceMap injection point resolving getCacheProxy receives that same singleton mock, even if it specifies a different cache or session name. This does not reproduce production’s cache- and session-aware resolution. Separate tests work when each test isolates a component that uses one cache. Splitting tests cannot supply distinct cache mocks to one component whose injection points all resolve getCacheProxy. For such a component, introduce application-level collaborators, each wrapping a cache operation, and mock those collaborators independently.

The explicitly selected, plain @Configuration supplies the test’s primary configuration, so Boot does not search for the production @SpringBootApplication class or load its explicit Coherence enablement. This bootstrap uses targeted imports without component scanning. @EnableAutoConfiguration enables Boot’s auto-configuration support, so the same three exclusions remain necessary. A @TestConfiguration alone supplements the primary configuration and does not prevent Boot from discovering it, even when supplied through classes.

Do not import or scan the production application configuration from this bootstrap. Check that imported components do not transitively import or scan configuration that enables or starts Coherence. Their dependencies still need appropriate test beans or mocks; selecting a different bootstrap does not provide them.

3. Configuration Properties

Additional configuration can be provided for instance via Spring Boot’s application.yaml or application.properties file. For instance YAML configuration for Spring Boot’s Coherence support may look like the following:

coherence:
  property-prefix: "coherence.properties."
  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: server, client (For both Coherence*Extend and gRPC)

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.

coherence.instance.type

Depends on session type. As soon as you specify a server session, it defaults to cluster

Type of the Coherence instance: cluster or client

coherence.server.startup-timeout

5m

Overrides the default startup-timeout when starting Coherence.

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

Many 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.

4. Coherence Cluster Setup

In order to set up Coherence clusters with Spring Boot, you can use the following approaches:

  • Co-locate Coherence instances with your application

  • Access a dedicated Coherence Cluster as a Client, either via gRPC or Coherence*Extend.

For an in-depth introduction to Coherence clusters, please consult the chapter Introduction to Coherence Clusters.

4.1. Co-located Coherence Clusters

In this setup, Coherence is started as part of your Spring Boot application. Each instance of your application will run Coherence and using the Tangosol Cluster Management Protocol (TCMP), they will form a Coherence cluster. This is typically the recommended approach for most use-cases and the default. Therefore, by just adding the coherence-spring-boot-starter Maven dependency, Spring Boot autoconfiguration for Coherence is enabled and will enable Coherence in Server (Clustered) mode.

If you need to provide additional configuration, e.g. to point to your own Coherence cache configuration file or to provide Coherence System Property Overrides, you can add those to your application.yaml file:

Coherence Configuration Properties
coherence:
  sessions:
    server:
      - name: default
        config: "coherence-cache-config.xml"  (1)
  logging:
    destination: slf4j                        (2)
coherence.wka: 127.0.0.1                      (3)
1 The Coherence cache configuration URI for the session (classpath resource)
2 Several Oracle Coherence system property overrides are directly mapped to Spring Boot properties
3 Alternatively, you can specify any Coherence system property override directly as well

4.2. Access Coherence Clusters as a Client

In this approach, your Spring Boot application will connect to a dedicated Coherence cluster as a client. This can be done either via Coherence*Extend or gRPC. For your Spring Boot application, the configuration is basically the same for both approaches. In your Spring Boot application.yaml file, you will need to specify the following:

Coherence Client Configuration
coherence:
  spring:
    - server:                           (1)
    - client:                           (2)
      - name: default
        config: remote-cache-config.xml (3)
coherence.tcmp.enabled: false           (4)
1 Disable the server (clustered) session
2 Enable the client session
3 The Coherence cache configuration URI for the client session, which contains the gRPC or Coherence*Extend-specific configuration
4 Disable TCMP
When setting up pure client connections to a Coherence cluster, you should ensure that TCMP is disabled. For more information, please see Disabling TCMP Communication in the Coherence reference guide.

An alternative to the yaml or properties configuration above is to specify a dedicated SessionConfigurationBean in your Spring Boot application.

Configure the Coherence Client using a SessionConfigurationBean
@Configuration
public class CoherenceClientConfig {
  @Bean
  public SessionConfigurationBean grpcSessionConfigurationBean() {
    final ClientSessionConfigurationBean sessionConfigurationBean = new ClientSessionConfigurationBean();
    sessionConfigurationBean.setName(SessionConfigurationBean.DEFAULT_SESSION_NAME);
    sessionConfigurationBean.setConfig("remote-cache-config.xml");
    return sessionConfigurationBean;
  }
}

In the configuration above the remote-cache-config.xml file will contain the relevant Coherence configuration for either Coherence*Extend or gRPC. The configuration for both approaches is described in the following sections.

4.2.1. gRPC

The main gRPC configuration is done in your coherence-cache-config.xml file. The configuration would look similar to the following:

Minimal gRPC Configuration
<?xml version="1.0"?>
<cache-config
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://xmlns.oracle.com/coherence/coherence-cache-config"
    xsi:schemaLocation="http://xmlns.oracle.com/coherence/coherence-cache-config coherence-cache-config.xsd">
    <caching-scheme-mapping>
        <cache-mapping>
            <cache-name>*</cache-name>                   (1)
            <scheme-name>remote-grpc</scheme-name>       (2)
        </cache-mapping>
    </caching-scheme-mapping>

    <caching-schemes>
        <remote-grpc-cache-scheme>                       (3)
            <scheme-name>remote-grpc</scheme-name>
            <service-name>RemoteGrpcCache</service-name> (4)
            <cluster-name>Mycluster</cluster-name>
        </remote-grpc-cache-scheme>
    </caching-schemes>
</cache-config>
1 The cache name * is a wildcard and will match all caches
2 The scheme name remote-grpc is used to map the all caches to the scheme
3 The remote-grpc cache is defined in the remote-grpc-cache-scheme XML element
4 The reference to the gRPC service name
For more information on gRPC, please consult the chapter on Getting Started with gRPC in the Coherence reference guide.

4.2.2. Coherence*Extend

The setup for Coherence*Extend is very similar to the gRPC setup. The main difference is that you will use the remote-cache-scheme XML element instead. The configuration would look similar to the following:

Minimal Coherence*Extend Configuration
<?xml version="1.0"?>
<cache-config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xmlns="http://xmlns.oracle.com/coherence/coherence-cache-config"
              xsi:schemaLocation="http://xmlns.oracle.com/coherence/coherence-cache-config coherence-cache-config.xsd">

    <caching-scheme-mapping>
        <cache-mapping>
            <cache-name>*</cache-name>                         (1)
            <scheme-name>remote</scheme-name>                  (2)
        </cache-mapping>
    </caching-scheme-mapping>

    <caching-schemes>
        <remote-cache-scheme>                                  (3)
            <scheme-name>remote</scheme-name>
            <service-name>ExtendTcpCacheService</service-name>
        </remote-cache-scheme>
    </caching-schemes>
</cache-config>
1 The cache name * is a wildcard and will match all caches
2 The scheme name remote is used to map the all caches to the scheme
3 The remote cache scheme is defined in the remote-cache-scheme XML element

The configuration above will use the name service to discover the Coherence cluster and thus the exposed Coherence*Extend port. However, you can also specify the host and port explicitly. Here is an example of the configuration where the Coherence*Extend host and port are specified explicitly:

Coherence*Extend Configuration with explicit host/port configuration
<?xml version="1.0"?>
<cache-config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xmlns="http://xmlns.oracle.com/coherence/coherence-cache-config"
              xsi:schemaLocation="http://xmlns.oracle.com/coherence/coherence-cache-config coherence-cache-config.xsd">

    <caching-scheme-mapping>
        <cache-mapping>
            <cache-name>*</cache-name>
            <scheme-name>remote</scheme-name>
        </cache-mapping>
    </caching-scheme-mapping>

    <caching-schemes>
        <remote-cache-scheme>
            <scheme-name>remote</scheme-name>
            <service-name>ExtendTcpCacheService</service-name>
            <initiator-config>
                <tcp-initiator>
                    <name-service-addresses>
                        <socket-address>
                            <address>127.0.0.1</address>
                            <port>7574</port>
                        </socket-address>
                    </name-service-addresses>
                </tcp-initiator>
                <outgoing-message-handler>
                    <request-timeout>5s</request-timeout>
                </outgoing-message-handler>
            </initiator-config>
        </remote-cache-scheme>
    </caching-schemes>
</cache-config>
For more information on Coherence*Extend, please consult the chapter on Getting Started with Coherence*Extend in the Coherence reference guide.

5. 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 values. Please see class CoherenceConfigClientProperties for details.

6. 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:

6.1. Configure Circuit Breakers with Resilience4j

Generally, it is recommended to configure and run Coherence as part of your application as a cluster member. However, caching can also be configured using Coherence in client mode via Coherence*Extend or gRPC. However, in client mode you may encounter failures and/or reliability situations due to network issues resulting in cache failures. In those situations, it would be desirable to retrieve the data from the persistence store instead, until the connectivity is being restored. Similarly, your application may encounter request timeout issues when retrieving data from the cache.

This is where the circuit breaker pattern can be quite helpful, allowing you to gracefully degrade functionality via configurable fallback methods. Spring Boot has excellent support via Resilience4j, a fault tolerance library.

Coherence Spring includes an example application that illustrates a basic circuit breaker use-case via Resilience4j. In this example a Spring Boot-based application has REST endpoints to retrieve Books:

  • GET /api/books - Retrieve all books

  • GET /api/books/1234 - Retrieve a single book

  • DELETE /api/books/1234 - Evict a book from the Coherence cache

By default, 2 books are inserted into the in-memory database AND into the Coherence cache. The application uses Spring’s cache abstraction backed by Coherence. The application is configured to connect to Coherence on a separate node via Coherence*Extend. The use-case of the application is that when you shut down the Coherence server, the application won’t be able to retrieve cached domain data from Coherence. Instead, the Resilience4j circuit breaker will catch the connection exception and invoke a fallback method. In this case the data is returned from the main persistence store, bi-passing the Spring cache until the connection to the Coherence server has been restored.

With security-hardened Coherence 26.10, the application permits its exact Book payload in META-INF/coherence/security-config.xml. The permission is checked in the application JVM when cached Extend response values are deserialized. The model-free server stores and returns binary values on this path. HTTP 200 can also come from a database fallback after a cache failure; the sample’s BookCacheIT verify actual individual and collection cache hits independently. See the Sample README for the permission boundary and focused positive and missing-permission checks. The default Coherence version remains 26.04. Use released Coherence 26.10 on Java 21 for hardened checks; see Compatibility for runtime requirements and qualification limits.

6.1.1. Running the Example

The example application consists of 2 applications:

  • circuit-breaker-cache-demo-server - The stand-alone Coherence instance

  • circuit-breaker-cache-demo-app - The client application that will connect to the Coherence server via Coherence*Extend

Let’s first run the server:

./mvnw spring-boot:run -pl samples/circuit-breaker-cache-demo/circuit-breaker-cache-demo-server

Now we need to run the actual application:

./mvnw spring-boot:run -pl samples/circuit-breaker-cache-demo/circuit-breaker-cache-demo-app

When the application starts, 2 books are added not only to the persistence store (HSQLDB) but also to the Coherence cache. However, this is not true for the retrieval of all books in this example.

Get all books

When you retrieve a list of all books. You will see that the main relevant business method is executed and the data retrieved from the database. But at this point the collection of books is added to the Coherence cache for the first time.

List all books
curl -i \
  -H "Accept: application/json" \
  -H "Content-Type:application/json" \
  -X GET "http://localhost:8090/api/books"

Thus, when you retrieve the list of books again, you will see in the logs:

No cache entry for key 'SimpleKey []' in cache(s) [allBooks]

Get a Single Book

When retrieving a single book, on the other side, the book is retrieved from the Coherence cache right away.

Get a single book
curl -i \
  -H "Accept: application/json" \
  -H "Content-Type:application/json" \
  -X GET "http://localhost:8090/api/books/1"

You will see something like:

Cache entry for key '1' found in cache 'books'

Let’s evict the book from the Coherence cache:

Evict book with id 1 from the Coherence Cache
curl -i \
  -H "Accept: application/json" \
  -H "Content-Type:application/json" \
  -X DELETE "http://localhost:8090/api/books/1"

Now, when you retrieve the book again, it will be retrieved from the persistence store instead. Let’s do something more interesting. When retrieving a single book we added a special case to the business service, where the retrieval of a book with id 42 will cause a BusinessException to be thrown.

Get a single book throwing a business exception
curl -i \
  -H "Accept: application/json" \
  -H "Content-Type:application/json" \
  -X GET "http://localhost:8090/api/books/42"

As you may notice, an Internal Server Error (HTTP status 500) is returned to you. Additionally, a BusinessException was thrown and handled by a Resilience4j fallback method.

Resilience4j selects fallback methods based on the specificity of the thrown Exceptions in relation to the exception declared in the fallback method. Thus, if you have multiple fallback methods, the method with the most specific exception is being chosen. Furthermore, it is important to know that expected exceptions (e.g. Business Exceptions) that you have included in the list of ignoreExceptions via application.yaml:

  • resilience4j.circuitbreaker.configs.*.ignoreExceptions

will also trigger the execution of fallBack methods, but it will not change the state of the circuit breaker.

Next, we will first shut down the Coherence server, and then we try to retrieve a single book with id 1:

Get a single book again
curl -i \
  -H "Accept: application/json" \
  -H "Content-Type:application/json" \
  -X GET "http://localhost:8090/api/books/1"

As you see, the JSON response is still the same (The book data is returned). However, when you look at the logs, you will see:

getBook fallback method (For Throwable) was called: Unable to locate ProxyService 'ExtendTcpCacheService' ...

So basically, the CacheManager was unable to connect to the Coherence instance and therefore the Circuit Breaker kicked in, calling the fallback method instead, and thus returning the Book not from the cache but from the persistence store.

6.1.2. Monitoring the Circuit Breaker

Spring Boot and Resilience4j also provide facilities to monitor the state of the Circuit Breaker via Spring Boot’s health-endpoint as well as its circuit breaker events endpoint:

Spring Boot Health Endpoint
{
  "status":"UP",
  "components":{
    "circuitBreakers":{
      "status":"UNKNOWN",
      "details":{
        "coherence":{
          "status":"CIRCUIT_OPEN",
          "details":{
            "failureRate":"100.0%",
            "failureRateThreshold":"5.0%",
            "slowCallRate":"0.0%",
            "slowCallRateThreshold":"100.0%",
            "bufferedCalls":3,
            "slowCalls":0,
            "slowFailedCalls":0,
            "failedCalls":3,
            "notPermittedCalls":8,
            "state":"OPEN"
          }
        }
      }
    },
    "db":{
      "status":"UP",
      "details":{
        "database":"HSQL Database Engine",
        "validationQuery":"isValid()"
      }
    },
    "diskSpace":{
      "status":"UP",
      "details":{
        "total":2000796545024,
        "free":1490744430592,
        "threshold":10485760,
        "exists":true
      }
    },
    "ping":{
      "status":"UP"
    }
  }
}

For demonstrating purposes we enabled the relevant health endpoints via Spring Boot configuration in application.yaml:

management.endpoints.web.exposure.include: "*"
management.endpoint.health.show-details: always

You may not want to do this in production. This is solely for demonstration purposes, especially as no security is configured for this application.

6.1.3. Add Resilience4j Dependencies

In order to use Resilience4j in your Coherence Spring project with Spring Boot, you need to add the following dependencies:

Example 2. Resilience4j Spring Boot Dependency
Maven
<dependency>
    <groupId>io.github.resilience4j</groupId>
    <artifactId>resilience4j-spring-boot4</artifactId>
    <version>2.4.0</version>
</dependency>
Gradle
implementation("io.github.resilience4j:resilience4j-spring-boot4:2.4.0")

6.1.4. Resilience4j Annotations

In order to add circuit-breaker capabilities to our @Cacheable business methods in DefaultBookService, we simply add the @CircuitBreaker annotations, e.g.:

@Cacheable("allBooks")
@CircuitBreaker(name = "coherence", fallbackMethod = "getAllBooksFallback")
@Override
public List<Book> getAllBooks() {
 ...
}

The key is the specified fallback method: whenever an exception occurs, the fallback method is being executed. You can have multiple fallback methods, specifying different exception types. Resilience4j will then select the fallback methods based on the specificity of the thrown exception.

When dealing with fallback method, it may at times be necessary to call other methods of the same services that you expect to be proxied, e.g. have applied annotations etc. However, when calling other methods in the same service, you are calling those methods without the relevant AOP aspects applied to them. You may either need to refactor those methods into another Spring bean or can actually inject the same service into the service. This type of injection call self injection or self autowiring has been supported since Spring 4.3.

7. 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.

For this baseline, use coherence-hibernate-cache-7 4.1.0 with Hibernate ORM 7.4.5.Final. The adapter supports ORM 7.4.x; Spring Boot’s managed ORM version must be overridden when using it. See Hibernate version selection and dependencies.

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.v7.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.v7.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.

Coherence Spring uses Coherence Hibernate 4.1.0. The v7 adapter packages META-INF/coherence/security-config.xml with executable processor and cache payload declarations for security-hardened Coherence 26.10. Application-specific serialized values may require additional permissions. The sample’s HibernateCacheIT requires actual cross-member entity, query and timestamp cache hits with zero SQL on measured reads. Metadata presence alone does not establish runtime qualification. Coherence 26.04 remains the project default. Use released Coherence 26.10 on Java 21 for hardened checks; see Compatibility for runtime requirements and qualification limits.

7.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"}

7.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-5.0.0.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.jpa.HibernateHints.HINT_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"

8. Spring Session Support

Coherence Spring also provides support for Spring Session. This includes auto-configuration support as well as a set of Coherence-specific configuration properties. Before you continue, please consider reading the chapter on Coherence Spring Session first.

For a Spring Boot servlet web application, select coherence-spring-session-boot-starter. It supplies the general Coherence starter, coherence-spring-session and Boot’s spring-boot-session, including spring-session-core. Keep an explicit Coherence runtime and the application’s servlet web dependencies. The following recipes assume the Spring Boot parent or BOM manages Boot versions; Security and Actuator remain application choices. For Gradle platform setup, see Update dependency management.

Example 3. Add Coherence Spring Session Support
Maven
<dependencies>
    <dependency>
        <groupId>com.oracle.coherence.spring</groupId>
        <artifactId>coherence-spring-session-boot-starter</artifactId>
        <version>5.0.0</version>
    </dependency>
    <dependency>
        <groupId>com.oracle.coherence.ce</groupId>
        <artifactId>coherence</artifactId>
        <version>26.04</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-webmvc</artifactId>
    </dependency>
</dependencies>
Gradle
dependencies {
    implementation("com.oracle.coherence.spring:coherence-spring-session-boot-starter:5.0.0")
    implementation("com.oracle.coherence.ce:coherence:26.04")
    implementation("org.springframework.boot:spring-boot-starter-webmvc")
}

With these dependencies, Boot discovery activates CoherenceSpringSessionAutoConfiguration automatically in a servlet web application and creates the Coherence repository and springSessionRepositoryFilter. No @EnableCoherenceHttpSession annotation is required. The general starter alone does not supply Spring Session; the old general-starter plus session-library combination also needs Boot Session explicitly. See the 5.x dependency migration for the manual combination.

Auto-configuration backs off in these situations:

  • Set property coherence.spring.session.enabled to false

  • Define spring.session.store-type. Any value, including an empty value or none, deactivates Coherence’s auto-configuration. This property does not install or configure another store by itself.

  • Supply an application-owned SessionRepository, including one enabled through @EnableCoherenceHttpSession. The application then owns its repository and HTTP-session configuration. A bare repository bean does not create an HTTP filter; configure that explicitly, for example with @EnableSpringHttpSession when supplying the repository.

This integration supports servlet applications, including embedded servers and Boot WAR deployments. It does not provide reactive WebSession support or enable HTTP sessions in non-web applications. Required Session, Boot Session and servlet classes must be present; coherence.spring.session.enabled=true cannot supply a missing dependency. After migration, verify the Coherence repository, springSessionRepositoryFilter, and stored state across HTTP requests with the same cookie. Application startup alone does not establish that HTTP-session integration is active.

The following Coherence-specific configuration properties are available:

Table 2. Coherence Configuration Properties
Key Default Value Description

coherence.spring.session.enabled

true

Set to false to disable 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.

coherence.spring.session.use-entry-processor

true

If true, a Coherence Entry Processor will be used for handling updates to the persisted HTTP session.

9. 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.

10. Coherence Metrics

Metrics are an application-level choice. The general coherence-spring-boot-starter does not add Boot’s metrics module or Micrometer core to an application’s runtime classpath. To publish Coherence Metrics, add coherence-micrometer and make a Micrometer MeterRegistry available using one of the following configurations.

10.1. Use Spring Boot Actuator

Applications that use Actuator should add its starter. Actuator already includes Boot’s metrics starter, so the two Boot starters are alternatives and should not both be declared. These examples assume that the Spring Boot parent or BOM manages the Boot dependency version. For Gradle platform setup, see Update dependency management.

Example 4. Coherence Metrics with Spring Boot Actuator
Maven
<dependencies>
    <dependency>
        <groupId>com.oracle.coherence.spring</groupId>
        <artifactId>coherence-spring-boot-starter</artifactId>
        <version>5.0.0</version>
    </dependency>
    <dependency>
        <groupId>com.oracle.coherence.ce</groupId>
        <artifactId>coherence</artifactId>
        <version>26.04</version>
    </dependency>
    <dependency>
        <groupId>com.oracle.coherence.ce</groupId>
        <artifactId>coherence-micrometer</artifactId>
        <version>26.04</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
</dependencies>
Gradle
dependencies {
    implementation("com.oracle.coherence.spring:coherence-spring-boot-starter:5.0.0")
    implementation("com.oracle.coherence.ce:coherence:26.04")
    implementation("com.oracle.coherence.ce:coherence-micrometer:26.04")
    implementation("org.springframework.boot:spring-boot-starter-actuator")
}

10.2. Use Boot metrics without Actuator

Applications that want Boot to configure metrics without the full Actuator starter can add the dedicated metrics starter instead.

Example 5. Coherence Metrics without Spring Boot Actuator
Maven
<dependencies>
    <dependency>
        <groupId>com.oracle.coherence.spring</groupId>
        <artifactId>coherence-spring-boot-starter</artifactId>
        <version>5.0.0</version>
    </dependency>
    <dependency>
        <groupId>com.oracle.coherence.ce</groupId>
        <artifactId>coherence</artifactId>
        <version>26.04</version>
    </dependency>
    <dependency>
        <groupId>com.oracle.coherence.ce</groupId>
        <artifactId>coherence-micrometer</artifactId>
        <version>26.04</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-micrometer-metrics</artifactId>
    </dependency>
</dependencies>
Gradle
dependencies {
    implementation("com.oracle.coherence.spring:coherence-spring-boot-starter:5.0.0")
    implementation("com.oracle.coherence.ce:coherence:26.04")
    implementation("com.oracle.coherence.ce:coherence-micrometer:26.04")
    implementation("org.springframework.boot:spring-boot-starter-micrometer-metrics")
}

10.3. Supply an application-owned registry

An application can provide its own registry without adding Boot’s metrics module. For example, the coherence-micrometer dependency supplies Micrometer core, allowing the application to define a simple registry:

import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration(proxyBeanMethods = false)
class MetricsConfiguration {

    @Bean
    MeterRegistry meterRegistry() {
        return new SimpleMeterRegistry();
    }
}

Coherence binds its singleton Micrometer adapter to the selected registry when both the adapter and a MeterRegistry bean are available. If the application defines a CoherenceMicrometerMetrics bean, auto-configuration backs off and the application owns the binding. The integration does not necessarily register the adapter itself as a Spring bean. Creating a registry, binding Coherence meters, exposing an HTTP endpoint, and exporting meters to a monitoring backend are separate steps. In particular, a SimpleMeterRegistry does not export metrics to a monitoring service.

Spring Boot 4 moved registry auto-configuration from spring-boot-actuator-autoconfigure to spring-boot-micrometer-metrics. Under Spring Boot 4, the Coherence starter and coherence-micrometer alone still allow the application to start, but no registry is created automatically and Coherence metrics are not bound. Applications already using Actuator satisfy the new prerequisite.

When Boot manages the registry, the following property filters meters whose names begin with coherence:

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

This property does not remove metrics dependencies or disable other Boot metrics. An application that uses only its own registry is also responsible for configuring any desired Micrometer meter filters.

11. Spring Data Support

Coherence Spring’s support for Spring Data also contain auto-configuration support for Spring Boot. The auto-configuration is activated as soon as the Coherence Spring Data dependency is added to your Spring Boot project.

Example 6. Add Coherence Spring Data Support
Maven
<dependencies>
    <dependency>
        <groupId>com.oracle.coherence.spring</groupId>
        <artifactId>coherence-spring-boot-starter</artifactId>
        <version>5.0.0</version>
    </dependency>
    <dependency>
        <groupId>com.oracle.coherence.spring</groupId>
        <artifactId>coherence-spring-data</artifactId>
        <version>5.0.0</version>
    </dependency>
    <dependency>
        <groupId>com.oracle.coherence.ce</groupId>
        <artifactId>coherence</artifactId>
        <version>26.04</version>
    </dependency>
</dependencies>
Gradle
dependencies {
    implementation("com.oracle.coherence.spring:coherence-spring-boot-starter:5.0.0")
    implementation("com.oracle.coherence.spring:coherence-spring-data:5.0.0")
    implementation("com.oracle.coherence.ce:coherence:26.04")
}

There is no need to add the @EnableCoherenceRepositories annotation, as the Coherence Spring Data auto-configuration support, will automatically detect any Coherence repositories. In fact, adding @EnableCoherenceRepositories to your Spring Boot project, will cause auto-configuration to back-off.

Auto-configuration can also be de-activated by setting environment property coherence.spring.data.repositories.enabled to false.