eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Summer Sale 2026 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

Course – Summer Sale 2026 – NPI (cat=Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

1. Overview

HashiCorp’s Vault is a tool to store and secure secrets. Vault, in general, solves the software development security problem of how to manage secrets. To learn more about it, check out our article here.

Spring Vault provides Spring abstractions to the HashiCorp’s Vault.

In this tutorial, we’ll go over an example of how to store and retrieve secrets from the Vault.

2. Maven Dependencies

To start with, let’s take a look at the dependencies we need to start working with Spring Vault:

<dependencies>
    <dependency>
        <groupId>org.springframework.vault</groupId>
        <artifactId>spring-vault-core</artifactId>
        <version>3.1.1</version>
    </dependency>
</dependencies>

The latest version of spring-vault-core can be found on Maven Central.

3. Configuring Vault

Let’s now go through the steps needed to configure Vault.

3.1. Creating a VaultTemplate

To secure our secrets, we’ll need an instance of the VaultTemplate class for which we need VaultEndpoint and TokenAuthentication instances:

VaultTemplate vaultTemplate = new VaultTemplate(new VaultEndpoint(), 
  new TokenAuthentication("00000000-0000-0000-0000-000000000000"));

3.2. Creating a VaultEndpoint

There’re a few ways to instantiate VaultEndpoint. Let’s take a look at some of them.

The first one is to simply instantiate it using a default constructor, which will create a default endpoint pointing to http://localhost:8200:

VaultEndpoint endpoint = new VaultEndpoint();

Another way is to create a VaultEndpoint by specifying Vault’s host and port:

VaultEndpoint endpoint = VaultEndpoint.create("host", port);

And finally, we can also create it from the Vault URL:

VaultEndpoint endpoint = VaultEndpoint.from(new URI("vault uri"));

There are a few things to notice here – Vault will be configured with a root token of 00000000-0000-0000-0000-000000000000 to run this application.

In our example, we’ve used  TokenAuthentication, but there are other authentication methods supported as well.

4. Configuring Vault Beans Using Spring

With Spring, we can configure the Vault in a couple of ways. One is by extending the AbstractVaultConfiguration, and the other one is by using EnvironmentVaultConfiguration, which makes use of Spring’s environment properties.

We’ll now go over both ways.

4.1. Using AbstractVaultConfiguration

Let’s create a class that extends AbstractVaultConfiguration, to configure Spring Vault:

@Configuration
public class VaultConfig extends AbstractVaultConfiguration {

    @Override
    public ClientAuthentication clientAuthentication() {
        return new TokenAuthentication("00000000-0000-0000-0000-000000000000");
    }

    @Override
    public VaultEndpoint vaultEndpoint() {
        return VaultEndpoint.create("host", 8020);
    }
}

This approach is similar to what we’ve seen in the previous section. What’s different is that we’ve used Spring Vault to configure Vault beans by extending the abstract class AbstractVaultConfiguration.

We just have to provide the implementation to configure VaultEndpoint and ClientAuthentication.

4.2. Using EnvironmentVaultConfiguration

We can also configure Spring Vault using the EnviromentVaultConfiguration:

@Configuration
@PropertySource(value = { "vault-config.properties" })
@Import(value = EnvironmentVaultConfiguration.class)
public class VaultEnvironmentConfig {
}

EnvironmentVaultConfiguration makes use of Spring’s PropertySource to configure Vault beans. We just need to supply the properties file with some acceptable entries.

More information on all of the predefined properties can be found in the official documentation.

To configure the Vault, we need at least a couple of properties:

vault.uri=https://localhost:8200
vault.token=00000000-0000-0000-0000-000000000000

5. Securing Secrets

We’ll create a simple Credentials class that maps to username and password:

public class Credentials {

    private String username;
    private String password;
    
    // standard constructors, getters, setters
}

Now, let’s see how we can secure our Credentials object using the VaultTemplate:

Credentials credentials = new Credentials("username", "password");
VaultKeyValueOperations vaultKeyValueOperations = vaultTemplate.opsForKeyValue("credentials/myapp", 
  VaultKeyValueOperationsSupport.KeyValueBackend.KV_2)
vaultKeyValueOperations.put(credentials.getUsername(), credentials);

We must note that we used an instance of VaultKeyValueOperations as it supports both versioned and unversioned key-value backends.

Next, we’ll see how to access them.

6. Accessing Secrets

We can access the secured secrets using the get() method in VaultKeyValueOperations, which returns the VaultResponseSupport as a response:

VaultResponseSupport response = vaultKeyValueOperations.get(username, Credentials.class);
String username = response.getData().getUsername();
String password = response.getData().getPassword();

Our secret values are now ready.

7. Vault Repositories

Vault repository is a handy feature that comes with Spring Vault 2.0. It applies Spring Data’s repository concept on top of Vault.

Let’s dig deep to see how to use this new feature for unversioned key-value backends.

7.1. @Secret and @Id Annotations

Spring provides these two annotations to mark the objects we want to persist inside Vault.

So first, we need to decorate our domain type Credentials:

@Secret(backend = "credentials", value = "myapp")
public class Credentials {

    @Id
    private String username;
    // Same code
]

The value attribute of the @Secret annotation serves to distinguish the domain type. The backend attribute denotes the secret backend mount.

On the other hand, @Id simply demarcates the identifier of our object.

7.2. Vault Repository

Now, let’s define a repository interface that uses our domain object Credentials:

public interface CredentialsRepository extends CrudRepository<Credentials, String> {
}

As we can see, our repository extends CrudRepository, which provides basic CRUD and query methods.

Next, let’s inject CredentialsRepository into CredentialsService and implement some CRUD methods:

public class CredentialsService {

    private final VaultTemplate vaultTemplate;
    private CredentialsRepository credentialsRepository;
    private final VaultKeyValueOperations vaultKeyValueOperations;

    @Autowired
    public CredentialsService(VaultTemplate vaultTemplate, CredentialsRepository credentialsRepository) {
        this.vaultTemplate = vaultTemplate;
        this.credentialsRepository = credentialsRepository;
        this.vaultKeyValueOperations = vaultTemplate.opsForKeyValue("credentials/myapp", 
      VaultKeyValueOperationsSupport.KeyValueBackend.KV_2);
    }

    public Credentials saveCredentials(Credentials credentials) {
        return credentialsRepository.save(credentials);
    }

    public Optional<Credentials> findById(String username) {
        return credentialsRepository.findById(username);
    }
}

Now that we’ve added all the missing pieces of the puzzle, let’s confirm that everything works as excepted using test cases.

First, let’s start with a test case for the save() method:

@Test
public void givenCredentials_whenSave_thenReturnCredentials() throws InterruptedException {
    Assume.assumeTrue("v1".equals(API_VERSION));

    credentialsService = new CredentialsService(vaultTemplate, credentialsRepository);
    // Given
    Credentials credentials = new Credentials("login", "password");

    // When
    Credentials savedCredentials = credentialsService.saveCredentials(credentials);

    // Then
    assertNotNull(savedCredentials);
    assertEquals(credentials.getUsername(), savedCredentials.getUsername());
    assertEquals(credentials.getPassword(), savedCredentials.getPassword());
}

Lastly, let’s confirm the findById() method with a test case:

@Test
public void givenId_whenFindById_thenReturnCredentials() {
    // Given
    Assume.assumeTrue("v1".equals(API_VERSION));
    Credentials expectedCredentials = new Credentials("login", "p@ssw@rd");
    credentialsService.saveCredentials(expectedCredentials);

    // When
    Optional retrievedCredentials = credentialsService.findById(expectedCredentials.getUsername());

    // Then
    assertNotNull(retrievedCredentials);
    assertNotNull(retrievedCredentials.get());
    assertEquals(expectedCredentials.get().getUsername(), retrievedCredentials.getUsername());
    assertEquals(expectedCredentials.getPassword(), retrievedCredentials.get().getPassword());
}

We must note that we use the CredentialsRepository only for the unversioned (“v1“) key-value backend.

8. Conclusion

In this article, we’ve learned about the basics of Spring Vault with an example showing how the Vault works in typical scenarios.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Summer Sale 2026 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

Course – Summer Sale 2026 – NPI (All)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

eBook Jackson – NPI EA – 3 (cat = Jackson)