Documentation for version 1.3.0
1. Introduction
Spring Cloud Oracle, part of the Spring Cloud umbrella project, eases the integration with Oracle Database and hosted OCI Services. It offers a convenient way to interact with Oracle Database and OCI provided services using well-known Spring idioms and APIs, such as storage resources. Developers can build their application around the hosted services without having to worry about infrastructure or maintenance.
2. Getting Started
This section describes how to get started using Spring Cloud Oracle libraries.
2.1. Spring Cloud Oracle
Spring Cloud Oracle module dependencies can be used directly in Maven with a direct configuration of the module. The Spring Cloud Oracle module includes all transitive dependencies for the Spring modules, and the OCI SDK that are needed to operate the modules. The general dependency configuration will look like this:
<dependencies> <dependency> <groupId>com.oracle.cloud.spring</groupId> <artifactId>spring-cloud-oci-starter</artifactId> <version>{spring-cloud-oci-version}</version> </dependency> </dependencies>
Different modules can be included by replacing the module name with the respective one (for example, spring-cloud-oci-starter-storage
instead of spring-cloud-oci-starter
)
2.1.1. Starter Dependencies
Spring Cloud Oracle offers starter dependencies through Maven to easily depend on different modules of the library. Each starter contains all the dependencies and transitive dependencies needed to begin using their corresponding Spring Cloud Oracle module.
For example, to write a Spring application with Cloud Storage, you include the spring-cloud-oci-starter-storage
dependency in your project.
You do not need to include the underlying spring-cloud-oci-storage
dependency, because the starter
dependency includes it.
A summary of these artifacts is provided here.
Spring Cloud Oracle Starter | Description | Maven Artifact Name |
---|---|---|
Core |
Automatically configure authentication |
|
Object Storage |
Provides integrations with OCI Cloud Storage |
2.2. Learning Spring Cloud Oracle
There are a variety of resources to help you learn how to use Spring Cloud Oracle libraries.
2.2.1. Sample Applications
The easiest way to learn how to use Spring Cloud Oracle is to consult the sample applications on Github. Spring Cloud Oracle provides sample applications which demonstrate how to use every integration in the library. The following table highlights several samples of the most used integrations in Spring Cloud Oracle.
OCI Integration | Sample Application |
---|---|
Cloud Storage |
|
Cloud Notification |
|
Cloud Generative AI |
|
Cloud Logging |
|
Cloud Streaming |
|
Cloud Function |
|
Cloud Queue |
|
Oracle Autonomous Database |
|
Generative AI |
|
Vault |
Each sample application demonstrates how to use Spring Cloud Oracle libraries in context and how to setup the dependencies for the project. The applications are fully functional and can be deployed to OCI as well.
3. Spring Cloud Oracle - OCI Core
Spring Cloud Oracle provides a Spring Boot starter to auto-configure the core components.
Maven coordinates:
<dependency>
<groupId>com.oracle.cloud.spring</groupId>
<artifactId>spring-cloud-oci-starter</artifactId>
</dependency>
Gradle coordinates:
dependencies {
implementation("com.oracle.cloud.spring:spring-cloud-oci-starter")
}
3.1. Authentication Configuration
Spring Cloud Oracle allows you to authenticate with OCI using various available options.
3.1.1. Configuration File Based Authentication
By default, configuration file based authentication is enabled. To set it explicitly, set the property spring.cloud.oci.config.type
to FILE
. The following are optional configurations to set a custom configuration profile name and file name.
spring.cloud.oci.config.profile = DEFAULT spring.cloud.oci.config.file = <FILE_PATH>
For further details about the Authentication configuration file, refer SDK and CLI Configuration File
3.1.2. Simple Authentication
Set the property spring.cloud.oci.config.type
to SIMPLE
and add the following properties:
spring.cloud.oci.config.type = SIMPLE spring.cloud.oci.config.userId = ocid1.user.oc1..<unique_ID> spring.cloud.oci.config.tenantId = ocid1.tenancy.oc1..<unique_ID> spring.cloud.oci.config.fingerprint = <FINGERPRINT> spring.cloud.oci.config.privateKey = <PRIVATE_KEY_FILE_PATH> spring.cloud.oci.config.passPhrase = <PASS_PHRASE> spring.cloud.oci.config.region = <REGION>
Note: All the preceding properties are mandatory except spring.cloud.oci.config.passPhrase
3.1.3. Instance Principal Configuration
Set the config.type to INSTANCE_PRINCIPAL
as shown here.
spring.cloud.oci.config.type = INSTANCE_PRINCIPAL
For further details, refer to OCI Instance Principal Authentication
3.1.4. Resource Principal Configuration
Set the config.type to RESOURCE_PRINCIPAL
as shown here.
spring.cloud.oci.config.type = RESOURCE_PRINCIPAL
For further details, refer to OCI Resource Principal Authentication
3.1.5. Session token Configuration
Set the config.type to SESSION_TOKEN
as shown here.
spring.cloud.oci.config.type = SESSION_TOKEN
3.1.6. Workload Identity Configuration
Set the config.type to WORKLOAD_IDENTITY
as shown here.
spring.cloud.oci.config.type = WORKLOAD_IDENTITY
For further details, refer to OKE Workload Identity Authentication
For further details, refer to docs.oracle.com/en-us/iaas/Content/API/Concepts/sdk_authentication_methods.htm#ariaid-title12
3.2. Region Configuration
OCI services are available in different regions. Based on the custom requirements, you can host the application on different OCI regions. The following configuration allows you to set a specific region for the entire application.
spring.cloud.oci.region.static = us-ashburn-1
Region value set in the preceding property takes precedence over the property spring.cloud.oci.config.region
and region
from the Authentication configuration file
3.3. Compartment Configuration
A compartment is a logical container, used to organize and control access to the OCI Resources (Compute, Storage, Network, Load Balancer, etc.) created within that compartment. The following configuration allows you to set the default compartment for your application.
spring.cloud.oci.compartment.static = <COMPARTMENT_OCID>
4. Autonomous Database
Autonomous Database is a data management service built on self-driving Oracle Autonomous Database technology to deliver automated patching, upgrades, and tuning, including performing all routine database maintenance tasks while the system is running, without human intervention.
Maven coordinates:
<dependency>
<groupId>com.oracle.cloud.spring</groupId>
<artifactId>spring-cloud-oci-starter-adb</artifactId>
</dependency>
Gradle coordinates:
dependencies {
implementation("com.oracle.cloud.spring:spring-cloud-oci-starter-adb")
}
4.1. Using Autonomous Database
The starter automatically configures and registers an AutonomousDb
bean in the Spring application context.
The AutonomousDb
bean (Javadoc) can be used to create an Autonomous Database, get details of an Autonomous Database,
delete an Autonomous Database and generate a wallet for an Autonomous Database.
@Autowired
AutonomousDb autonomousDatabase;
public void createAutonomousDatabase() {
autonomousDatabase.createAutonomousDatabase(
databaseName, compartmentId, adminPassword, dataStorageSizeInGBs, computeCount);
}
public void getAutonomousDatabase() {
AutonomousDbDetails response = autonomousDatabase.getAutonomousDatabase(databaseId);
}
public void getAutonomousDatabaseWallet() {
GenerateAutonomousDatabaseWalletResponse response = autonomousDatabase.generateAutonomousDatabaseWallet(databaseId, password);
InputStream is = response.getInputStream();
int ContentLength = response.getContentLength();
// read the InputStream to get the wallet
}
public void deleteAutonomousDatabase() {
DeleteAutonomousDatabaseResponse response = autonomousDatabase.deleteAutonomousDatabase(databaseId);
}
4.2. Configuration
The Spring Boot Starter for Oracle Autonomous Database provides the following configuration options:
Name |
Description |
Required |
Default value |
|
Enables the OCI Autonomous Database APIs. |
No |
|
4.3. Sample
A sample application provided here contains the examples to demonstrates the usage of OCI Spring Cloud Autonomous Database module.
5. Email Delivery
Email Delivery module provides an implementation of the Spring Mail interface, implementing MailSender and JavaMailSender interfaces to send email using OCI Email Delivery.
Maven coordinates:
<dependency>
<groupId>com.oracle.cloud.spring</groupId>
<artifactId>spring-cloud-oci-starter-email</artifactId>
</dependency>
Gradle coordinates:
dependencies {
implementation("com.oracle.cloud.spring:spring-cloud-oci-starter-email")
}
5.1. Configuring Email Delivery
Email Delivery uses the Spring Mail SMTP configuration properties to configure MailSender and JavaMailSender beans. Create SMTP credentials for OCI and use these to configure your username and password in Spring.
Your OCI SMTP endpoint can be found on the OCI Email Delivery Console.
spring:
mail:
host: ${OCI_SMTP_HOST}
username: ${OCI_SMTP_USERNAME}
password: ${OCI_SMTP_PASSWORD}
# Port 25 or 587 may be used. 587 is default.
port: 587
5.2. Using MailSender
For simple emails, use the MailSender interface. The following sample shows how to send an email with the MailSender interface.
@Service
public class EmailService {
private final MailSender mailSender;
public EmailService(@Qualifier("ociMailSender") MailSender mailSender) {
this.mailSender = mailSender;
}
public void sendSimpleMail(
String from,
String to,
String subject,
String text
) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setSubject(subject);
message.setText(text);
mailSender.send(message);
}
}
5.3. Using JavaMailSender
For more complex emails, such as those with attachments, use the JavaMailSender interface. The following example shows how to send an email with the JavaMailSender API.
@Service
public class EmailService {
private final JavaMailSender javaMailSender;
public EmailService(@Qualifier("ociJavaMailSender") JavaMailSender javaMailSender) {
this.javaMailSender = javaMailSender;
}
public void sendJavaMail(
String from,
String to,
String subject,
String text,
File fileAttachment
) throws MessagingException {
MimeMessage message = javaMailSender.createMimeMessage();
Multipart multipartContent = new MimeMultipart();
MimeBodyPart textContent = new MimeBodyPart();
textContent.setContent(text, "text/html");
multipartContent.addBodyPart(textContent);
MimeBodyPart attachmentContent = new MimeBodyPart();
DataSource source = new FileDataSource(fileAttachment);
attachmentContent.setDataHandler(new DataHandler(source));
attachmentContent.setFileName(fileAttachment.getName());
multipartContent.addBodyPart(attachmentContent);
message.setFrom(from);
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject(subject);
message.setContent(multipartContent);
javaMailSender.send(message);
}
}
5.4. Sample
A sample application provided here contains examples that demonstrate the usage of Spring Cloud Oracle Email module.
6. Cloud Functions
OCI Functions is a fully managed, multi-tenant, highly scalable, on-demand, Functions-as-a-Service platform. It is built on enterprise-grade Oracle Cloud Infrastructure and powered by the Fn Project open source engine. Use OCI Functions when you want to focus on writing code to meet business needs. The Spring Cloud Oracle module for OCI Functions allows to invoke an OCI Function. A Spring Boot starter is provided to autoconfigure the Function component.
Maven coordinates:
<dependency>
<groupId>com.oracle.cloud.spring</groupId>
<artifactId>spring-cloud-oci-starter-function</artifactId>
</dependency>
Gradle coordinates:
dependencies {
implementation("com.oracle.cloud.spring:spring-cloud-oci-starter-function")
}
6.1. Using Cloud Functions
The starter automatically configures and registers a Function
bean in the Spring application context.
The Function
bean (Javadoc) can be used to invoke a function with parameter inputs 'functionOcid' and 'endpoint'
@Autowired
private Function function;
public void invoke() {
InvokeFunctionResponse invokeFunctionResponse = function.invokeFunction(functionOcid, endpoint, mode, requestBody);
}
6.2. Configuration
The Spring Boot Starter for Oracle Cloud Function provides the following configuration options:
Name |
Description |
Required |
Default value |
|
Enables the OCI Functions APIs. |
No |
|
6.3. Sample
A sample application provided here contains the examples to demonstrates the usage of OCI Spring Cloud Function module.
7. Cloud Logging
OCI Logging service is a highly scalable and fully managed single pane of glass for all the logs in your tenancy. Logging provides access to logs from OCI resources. These logs include critical diagnostic information that describes how resources are performing and being accessed. Use Logging to enable, manage, and search Audit, Service, and Custom logs. The Spring Cloud Oracle module for OCI Logging allows ingesting logs associated with a logId. A Spring Boot starter is provided to autoconfigure the Logging component.
- Maven coordinates
<dependency>
<groupId>com.oracle.cloud.spring</groupId>
<artifactId>spring-cloud-oci-starter-logging</artifactId>
</dependency>
Gradle coordinates:
dependencies {
implementation("com.oracle.cloud.spring:spring-cloud-oci-starter-logging")
}
7.1. Using Cloud Logging
The starter automatically configures and registers a Logging
bean in the Spring application context.
The Logging
bean (Javadoc) can be used to ingest logs associated with a logId specified in the property spring.cloud.oci.logging.logId
within the application configuration file
@Autowired
private LogService logService;
public void putLog() {
PutLogsResponse response = logService.putLog("log-text");
}
7.2. Configuration
The Spring Boot Starter for Oracle Cloud Logging provides the following configuration options:
Name |
Description |
Required |
Default value |
|
Enables the OCI Logging APIs. |
No |
|
7.3. Sample
A sample application provided here contains the examples to demonstrates the usage of OCI Spring Cloud Logging module.
8. Generative AI
OCI Generative AI is a fully managed service that provides a set of state-of-the-art, customizable large language models (LLMs) that cover a wide range of use cases, including chat and creating text embeddings.
Maven coordinates:
<dependency>
<groupId>com.oracle.cloud.spring</groupId>
<artifactId>spring-cloud-oci-starter-gen-ai</artifactId>
</dependency>
Gradle coordinates:
dependencies {
implementation("com.oracle.cloud.spring:spring-cloud-oci-starter-gen-ai")
}
8.1. Using Generative AI Chat
The starter configures and registers a ChatModel
bean in the Spring application context.
The ChatModel
bean (Javadoc) can be used to interact with OCI Generative AI Chat Models.
@Autowired
private ChatModel chatModel;
public void embed() {
ChatResponse response = chatModel.chat("my chat prompt");
}
8.2. Using Generative AI Embedding
The starter configures and registers an EmbeddingModel
bean in the Spring application context.
The EmbeddingModel
bean (Javadoc) can be used to create text embeddings using OCI Generative AI Embedding Models.
@Autowired
private EmbeddingModel embeddingModel;
public void embed() {
EmbedTextResponse response = embeddingModel.embed("my embedding text");
}
8.3. Configuration
The Spring Boot Starter for Oracle Cloud Generative AI provides the following configuration options:
Name |
Description |
Required |
Default value |
|
Enables the OCI Generative AI Client. |
No |
|
|
Enables the OCI Generative AI Embedding APIs. |
No |
|
|
On-demand model ID to be used for embedding text. One of |
No |
|
|
Dedicated cluster endpoint used for embedding text. One of |
No |
|
|
Embedding model compartment. |
Yes |
|
|
How to truncate embedding text when it is greater than the model’s maximum tokens. May be |
No |
|
|
Enables the OCI Generative AI Chat APIs. |
No |
|
|
On-demand model ID to be used for chat. One of |
No |
|
|
Dedicated cluster endpoint used for chat. One of |
No |
|
|
Chat model compartment. |
Yes |
|
|
If specified, overrides the model’s prompt preamble. |
No |
|
|
Chat text generation temperature. Higher values are more random or creative. Learn more about temperature. |
No |
|
|
Ensures that only the most likely tokens with probabilities that sum to P are generated. Learn more about Top P. |
No |
|
|
Ensures that only the top K most probably tokens are considered in each step of text generation. Learn more about Top K. |
No |
|
|
Assigns a penalty for tokens that appear frequently. A higher value results in less repetitive text. |
No |
|
|
Assigns an equal penalty if a token appears in the text. A higher value results in less reptitive text. |
No |
|
|
Maximum response output tokens. Estimate 2-3 tokens per word. |
No |
|
8.4. Sample
A sample application provided here contains the examples to demonstrates the usage of OCI Spring Cloud Generative AI module.
9. Cloud Storage
Oracle Cloud Storage allows you to store any types of file. A Spring Boot starter is provided to autoconfigure the various Storage components.
Maven coordinates:
<dependency>
<groupId>com.oracle.cloud.spring</groupId>
<artifactId>spring-cloud-oci-starter-storage</artifactId>
</dependency>
Gradle coordinates:
dependencies {
implementation("com.oracle.cloud.spring:spring-cloud-oci-starter-storage")
}
9.1. Using Cloud Storage
The starter automatically configures and registers a Storage
bean in the Spring application context.
The Storage
bean (Javadoc) can be used to list, create, update or delete buckets and objects.
@Autowired
private Storage storage;
public void createBucketAndUploadFile() {
Bucket bucket = storage.createBucket("my-bucket");
storage.upload("my-bucket", "my-file.txt", inputStream, StorageObjectMetadata.builder().contentType("text/plain").build());
}
9.2. Cloud Storage Objects Spring Resources
Spring Resources are an abstraction for several low-level resources, such as file system files, classpath files, servlet context-relative files, etc. Spring Cloud Oracle adds a new resource type for Oracle Cloud Object Storage.
The Spring Resource Abstraction for Oracle Cloud Storage allows Object Storage objects to be accessed by their URL using the @Value
annotation or the Spring application context:
@Value("https://objectstorage.us-chicago-1.oraclecloud.com/n/${OCI_NAMESPACE}/b/${OCI_BUCKET}/o/${OCI_OBJECT}")
private Resource myObjectResource;
SpringApplication.run(...).getResource("Object Storage URL");
This creates a Resource
object that can be used to read the object, among other possible operations.
Currently, this resource is only readable.
9.3. Configuration
The Spring Boot Starter for Oracle Cloud Storage provides the following configuration options:
Name |
Description |
Required |
Default value |
|
Enables the OCI storage APIs. |
No |
|
9.4. Sample
A sample application provided here contains the examples to demonstrate the usage of OCI Spring Cloud Storage module.
10. Cloud Notifications
OCI Notifications is a highly available, low latency publish/subscribe (pub/sub) service that sends alerts and messages to Oracle Cloud Functions, email, SMS, and message delivery partners, including Slack, PagerDuty and custom HTTPS endpoint. Spring Cloud module for Oracle Cloud Notifications allows you to create a Topic, then create and publish messages to multiple subscription types such as Oracle Cloud Functions, email, SMS, Slack, PagerDuty and custom HTTPS endpoint. A Spring Boot starter is provided to autoconfigure the various Notification components.
Maven coordinates:
<dependency>
<groupId>com.oracle.cloud.spring</groupId>
<artifactId>spring-cloud-oci-starter-notification</artifactId>
</dependency>
Gradle coordinates:
dependencies {
implementation("com.oracle.cloud.spring:spring-cloud-oci-starter-notification")
}
10.1. Using Cloud Notifications
The starter automatically configures and registers a Notification
bean in the Spring application context.
The Notification
bean (Javadoc) can be used to create a Topic, create, list, get a Subscription, and publish messages to the Subscriptions in a Topic.
@Autowired
private Notification notification;
public void createTopic() {
CreateTopicResponse response = notification.createTopic("my-topic", <<compartment-ocid>>);
}
10.2. Configuration
The Spring Boot Starter for Oracle Cloud Notifications provides the following configuration options:
Name |
Description |
Required |
Default value |
|
Enables the OCI Notifications APIs. |
No |
|
10.3. Sample
A sample application provided here contains the examples to demonstrates the usage of OCI Spring Cloud Notification module.
11. Oracle NoSQL Database
Oracle NoSQL Database service offering on-demand throughput and storage based provisioning that supports JSON, Table and Key-Value datatypes, all with flexible transaction guarantees.
Maven coordinates:
<dependency>
<groupId>com.oracle.cloud.spring</groupId>
<artifactId>spring-cloud-oci-starter-nosql</artifactId>
</dependency>
Gradle coordinates:
dependencies {
implementation("com.oracle.cloud.spring:spring-cloud-oci-starter-nosql")
}
11.1. Using Oracle NoSQL Database
The starter automatically configures and registers a NosqlDBConfig
bean in the Spring application, allowing the use of Oracle NoSQL Database repositories.
spring:
cloud:
oci:
config:
type: file
region:
static: us-ashburn-1
Enable NoSQL repositories in your application by using the @EnableNosqlRepositories
annotation and extending the AbstractNosqlConfiguration
class.
import com.oracle.nosql.spring.data.config.AbstractNosqlConfiguration;
import com.oracle.nosql.spring.data.repository.config.EnableNosqlRepositories;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@EnableNosqlRepositories
public class MyApp extends AbstractNosqlConfiguration {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
NoSQL repositories and tables are simply defined by extending the NosqlRepository
interface and applying the @NosqlTable
annotation:
public interface BookRepository extends NosqlRepository<Book, Long> {
// Add repository methods as needed.
Iterable<Book> findByAuthor(String author);
Iterable<Book> findByTitle(String title);
}
@NosqlTable(tableName = "books")
public class Book {
@NosqlId(generated = true)
long id;
String title;
String author;
double price;
}
11.2. Configuration
The Spring Boot Starter for Oracle Cloud NoSQL Database provides the following configuration options:
Name |
Description |
Required |
Default value |
|
Enables the NoSQL DB Config. |
No |
|
11.3. Sample
A sample application provided here contains the examples to demonstrates the usage of OCI Spring Cloud NoSQL module.
12. Cloud Queues
OCI Queues is a highly available, low latency publish/subscribe (pub/sub) service, handles high volume transactional data that requires independently processed messages without loss or duplication. Spring Cloud module for Oracle Cloud Queues allows you to create a queue, get a queue, list queues, delete a queue, put messages, get messages, update messages and delete a message. A Spring Boot starter is provided to autoconfigure the various Queue components.
Maven coordinates:
<dependency>
<groupId>com.oracle.cloud.spring</groupId>
<artifactId>spring-cloud-oci-starter-queue</artifactId>
</dependency>
Gradle coordinates:
dependencies {
implementation("com.oracle.cloud.spring:spring-cloud-oci-starter-queue")
}
12.1. Using Cloud Queues
The starter automatically configures and registers a Queue
bean in the Spring application context.
The Queue
bean (Javadoc) can be used to create a queue, get a queue, list queues, delete a queue, put messages, get messages, update messages and delete a message.
@Autowired
private Queue queue;
public void createQueue() {
String queueId = queue.createQueue("my-queue", <<compartmentId>>, <<deadLetterQueueDeliveryCount>>, <<retentionInSeconds>>);
}
12.2. Configuration
The Spring Boot Starter for Oracle Cloud Queues provides the following configuration options:
Name |
Description |
Required |
Default value |
|
Enables the OCI Queue APIs. |
No |
|
12.3. Sample
A sample application provided here contains the examples to demonstrates the usage of OCI Spring Cloud Queue module.
13. Cloud Stream
OCI Streaming service provides a fully managed, scalable, and durable solution for ingesting and consuming high-volume data streams in real time. A Spring Boot starter is provided to autoconfigure the Streaming component.
- Maven coordinates
<dependency>
<groupId>com.oracle.cloud.spring</groupId>
<artifactId>spring-cloud-oci-starter-streaming</artifactId>
</dependency>
Gradle coordinates:
dependencies {
implementation("com.oracle.cloud.spring:spring-cloud-oci-starter-streaming")
}
13.1. Using Cloud Streaming
The starter automatically configures and registers a Streaming
bean in the Spring application context.
The Streaming
bean (Javadoc) can be used to create streamPool, stream in OCI and ingest and consume high-volume data streams with a streamId
@Autowired
private Streaming streaming;
public void putMessages() {
PutMessagesResponse response = streaming.putMessages(streamId, "key".getBytes(), "value"..getBytes());
}
public void getMessages() {
GetMessagesResponse response = streaming.getMessages(streamId, "cursor");
}
13.2. Configuration
The Spring Boot Starter for Oracle Cloud Stream provides the following configuration options:
Name |
Description |
Required |
Default value |
|
Enables the OCI Streaming APIs. |
No |
|
13.3. Sample
A sample application provided here contains the examples to demonstrates the usage of OCI Spring Cloud Streaming module.
14. OCI Vault
Vault can be used as a Spring property source for Vault secrets, and as an application bean for creating, updating, listing, and deleting secrets from a Vault.
Maven coordinates:
<dependency>
<groupId>com.oracle.cloud.spring</groupId>
<artifactId>spring-cloud-oci-starter-vault</artifactId>
</dependency>
Gradle coordinates:
dependencies {
implementation("com.oracle.cloud.spring:spring-cloud-oci-starter-vault")
}
14.1. Using VaultPropertySource
By configuring Vault as a property source, secrets can be dynamically loaded from OCI Vault into the Spring application context. For each Vault specified as a property source, Spring will inject secrets as properties identified by their name.
spring:
cloud:
oci:
config:
type: file
region:
static: us-ashburn-1
vault:
enabled: true
compartment: ${OCI_COMPARTMENT_ID}
# Spring will automatically refresh properties from Vault,
# if the property-refresh-interval is greater than 0ms.
# Defaults to 10 minutes.
property-refresh-interval: 10000ms
property-sources:
- vault-id: ${OCI_VAULT_ID}
// The secret "secretName" will be loaded from the Vault,
// and it's String value bound to the secretValue variable.
@Value("${secretname}")
String secretValue;
14.2. Using VaultTemplate
The starter automatically configures and registers an VaultTemplate
bean in the Spring application context.
The VaultTemplate
bean can be used to create, update, list, and delete secrets in an OCI Vault
spring:
cloud:
oci:
config:
type: file
region:
static: us-ashburn-1
vault:
compartment: ${OCI_COMPARTMENT_ID}
vault-id: ${OCI_VAULT_ID}
enabled: true
@Autowired
private VaultTemplate vaultTemplate;
public String getSecretByName(String secretName) {
GetSecretBundleByNameResponse bundle = vaultTemplate.getSecret(secretName);
return vaultTemplate.decodeBundle(bundle);
}
14.3. Configuration
The Spring Boot Starter for Oracle Vault provides the following configuration options:
Name |
Description |
Required |
Default value |
|
Enables the OCI Vault APIs. |
No |
|
|
Compartment for Vault APIs and property sources. |
Yes |
|
|
Vault OCID for Vault APIs. |
Yes |
|
|
Duration on which properties will be refreshed. |
No |
10m |
|
List of Vaults to use as Spring property sources. |
No |
|
|
Vault OCID to use as a property source. |
Yes |
14.4. Sample
A sample application provided here contains the examples to demonstrates the usage of OCI Spring Cloud Vault module.
15. Database Spring Boot Starters
15.1. AQ/JMS
This starter provides support for Oracle Transactional Event Queues (TxEventQ) and Oracle Advanced Queuing (AQ) as Java Message Service (JMS) providers. It depends on the Universal Connection Pool (UCP) starter.
Note: By default, the data Source and JMS Connection Factory that the starter injects into your application share the same database transaction. This means that you can start a transaction, read from a queue, perform an update operation, and then commit or rollback that whole unit of work, including the message consumption.
To add this starter to your project, add this Maven dependency:
<dependency>
<groupId>com.oracle.database.spring</groupId>
<artifactId>oracle-spring-boot-starter-aqjms</artifactId>
<version>24.3.0</version>
</dependency>
For Gradle projects, add this dependency:
dependencies {
implementation 'com.oracle.database.spring:oracle-spring-boot-starter-aqjms:24.3.0'
}
15.1.1. Using AQ/JMS
To configure your application to use Oracle Transactional Event Queues or Oracle Advanced Queuing, you must annotate you application with the @EnableJms
annotation, and create the
two following beans:
-
A
JmsListenerContainerFactory<?>
bean, which can be created as shown in the following example. Note that you can override settings if you need to. Also, note that the name of the method defines the name of the factory, which you will use when creating JMS listeners. -
A
MessageConverter
bean to map objects of your class representing the payload into a text based format (like JSON) that can be used in the actual messages.
Note: Any queues or topics that you want to use must be pre-created in the database. See [Sample Code](www.oracle.com/database/advanced-queuing/#rc30sample-code) for examples.
package com.example.aqjms;
import jakarta.jms.ConnectionFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jms.DefaultJmsListenerContainerFactoryConfigurer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
import org.springframework.jms.config.JmsListenerContainerFactory;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.support.converter.MappingJackson2MessageConverter;
import org.springframework.jms.support.converter.MessageConverter;
import org.springframework.jms.support.converter.MessageType;
@SpringBootApplication
@EnableJms
public class JmsSampleApplication {
@Bean
public JmsListenerContainerFactory<?> myFactory(ConnectionFactory connectionFactory,
DefaultJmsListenerContainerFactoryConfigurer configurer) {
DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
// This provides all Boot's defaults to this factory, including the message converter
configurer.configure(factory, connectionFactory);
// You could override some of Boot's defaults here if necessary
return factory;
}
@Bean
public MessageConverter jacksonJmsMessageConverter() {
MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
converter.setTargetType(MessageType.TEXT);
converter.setTypeIdPropertyName("_type");
return converter;
}
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(JmsSampleApplication.class, args);
}
}
To send a message to a JMS queue or topic, get an instance of the JmsTemplate
from the Spring Application context, and call the convertAndSend()
method specifying the name of the queue or
topic, and providing the object to be converted and sent in the payload of the message, as shown in the following example:
JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class);
jmsTemplate.convertAndSend("mailbox", new Email(-1, "info@example.com", "Hello"));
To receive messages from a JMS queue or topic, create a method that takes your message class, for example Email
, as input. Annotate the method with the @JmsListener
annotation, specifying the destination, that is the name of the queue or topic, and the container factory name that you created earlier, as shown in the following example:
package com.example.aqjms;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
@Component
public class Receiver {
@JmsListener(destination = "mailbox", containerFactory = "myFactory")
public void receiveMessage(Email email) {
System.out.println("Received <" + email + ">");
}
}
Note: The starter uses the configuration for spring.datasource
as the connection details for the Oracle Database hosting the queues and topics. If you wish to use a different configuration, you must use a named configuration, for example spring.datasource.txeventq
and use Java configuration and annotate the configuration with the standard Spring @Qualifier
annotation, specifying the correct name, for example txevevntq
.
15.2. Universal Connection Pool
This starter provides a connection (data source) to an Oracle Database using Universal Connection Pool, which provides an efficient way to use database connections.
To add this starter to your project, add this Maven dependency:
<dependency>
<groupId>com.oracle.database.spring</groupId>
<artifactId>oracle-spring-boot-starter-ucp</artifactId>
<version>24.3.0</version>
</dependency>
For Gradle projects, add this dependency:
dependencies {
implementation 'com.oracle.database.spring:oracle-spring-boot-starter-ucp:24.3.0'
}
15.2.1. Using Universal Connection Pool
An Oracle data source is injected into your application and can be used normally. You must configure the data source as shown below, and you should also add either Spring Data JDBC or Spring Data JPA to your project.
To configure the data source, provide a spring.datasource
object in your Spring application.yaml
, or equivalent, as shown in the following example. The oracleucp
entry is optional, and can be used to fine tune the configuration of the connection pool, if desired. For details of available settings, refer to the [JavaDoc](docs.oracle.com/en/database/oracle/oracle-database/21/jjuar/oracle/ucp/jdbc/UCPDataSource.html).
spring:
jpa:
hibernate:
ddl-auto: validate
properties:
hibernate:
dialect: org.hibernate.dialect.OracleDialect
format_sql: true
show-sql: true
datasource:
url: jdbc:oracle:thin:@//myhost:1521/pdb1
username: username
password: password
driver-class-name: oracle.jdbc.OracleDriver
type: oracle.ucp.jdbc.PoolDataSource
oracleucp:
connection-factory-class-name: oracle.jdbc.pool.OracleDataSource
connection-pool-name: AccountConnectionPool
initial-pool-size: 15
min-pool-size: 10
max-pool-size: 30
The spring.datasource.url
can be in the basic format (as previously shown), or in TNS format if your application uses Transparent Network Substrate (TNS).
Note that the connections to the database use the DEDICATED
server by default. If you wish to use SHARED
or POOLED
, you can append that to the basic URL, or add it to the TNS names entry. For example, to use database resident pooled connections, you would change the URL shown in the previous example to the following:
datasource:
url: jdbc:oracle:thin:@//myhost:1521/pdb1:pooled
If you are using TNS, add server=pooled
to the connect_data
. For example:
mydb_tp = (description=
(retry_count=20)
(retry_delay=3)
(address=(protocol=tcps)(port=1521)(host=myhost))
(connect_data=(service_name=pdb1)(server=pooled))
(security=(ssl_server_dn_match=yes)))
If you prefer to use Java configuration, the data source can be configured as shown in the following example:
import oracle.jdbc.pool.OracleDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
import java.sql.SQLException;
@Configuration
public class DataSourceConfiguration {
@Bean
public DataSource dataSource() throws SQLException {
OracleDataSource dataSource = new OracleDataSource();
dataSource.setUser("account");
dataSource.setPassword("password");
dataSource.setURL("jdbc:oracle:thin:@//myhost:1521/pdb1");
dataSource.setDataSourceName("AccountConnectionPool");
return dataSource;
}
}
15.3. Oracle Database Wallet
This starter provides authentication mechanisms for Oracle Database connections using Oracle Database Wallet, such as connections to Autonomous Database with mTLS enabled.
To add this starter to your project, add this Maven dependency:
<dependency>
<groupId>com.oracle.database.spring</groupId>
<artifactId>oracle-spring-boot-starter-wallet</artifactId>
<version>24.3.0</version>
</dependency>
For Gradle projects, add this dependency:
dependencies {
implementation 'com.oracle.database.spring:oracle-spring-boot-starter-wallet:24.3.0'
}
16. Configuration properties
To see the list of all OCI-related configuration properties see the Appendix page.
16.1. Configuration Refresh
The following properties are supported for Configuration auto-refresh at runtime without the need to restart applications
Name | Default |
---|---|
spring.cloud.oci.config.profile |
|
spring.cloud.oci.config.file |
NA |
spring.cloud.oci.config.type |
NA |
spring.cloud.oci.config.userId |
NA |
spring.cloud.oci.config.tenantId |
NA |
spring.cloud.oci.config.fingerprint |
NA |
spring.cloud.oci.config.privateKey |
NA |
spring.cloud.oci.config.passPhrase |
NA |
spring.cloud.oci.config.region |
NA |
spring.cloud.oci.region.static |
NA |
spring.cloud.oci.compartment.static |
NA |
spring.cloud.oci.logging.logId |
NA |
Spring Boot Actuator can be used to explicitly refresh the externalized configuration during runtime. Add the corresponding build dependency to enable the Actuator:
Maven:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
Gradle:
dependencies { implementation("org.springframework.boot:spring-boot-starter-actuator") }
Set management.endpoints.web.exposure.include=refresh
in the externalized configuration file of the Spring Boot Application to enable /actuator/refresh endpoint.
To refresh the updated Configuration properties at runtime make a POST API call to /actuator/refresh endpoint