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 – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Introduction

In this tutorial, we’re going to take a look at how to use custom TrustStore in Java. We’re going first to override the default TrustStore and then explore the ways to combine certificates from multiple TrustStores. We’ll also see what the known problems and challenges are and how we can surpass them.

2. Overriding Custom TrustStore

So, first, let’s override the default TrustStore. Most likely, it’s going to be the cacerts file located in lib/security/cacerts for JDK 9 and above. For JDKs below version 9, cacerts is located under jre/lib/security/cacerts. To override it, we need to pass a VM argument -Djavax.net.ssl.trustStore with the absolute path to the TrustStore to be used as the value. For instance, if we would launch JVM like this:

java -Djavax.net.ssl.trustStore=/path/to/another/truststore.p12 app.jar

Then, instead of cacerts, Java would use /path/to/another/truststore.p12 as a TrustStore.

However, this approach has a small problem. When we override the location of the TrustStore, the default cacerts TrustStore won’t be taken into account anymore. That means, that all of the trusted CA’s certificates that come with JDK preinstalled will now no longer be available.

3. Combining Multiple TrustStores

So, to solve the problem listed above, we can do either of two things:

  • include all of the default cacerts certificates into the new TrustStore that we want to use
  • try to programmatically ask Java to look into both TrustStores during the resolution of the trust of the entity

We’ll review both approaches below as they have their pros and cons.

4. Merging TrustStores

The first approach is a relatively simple solution to the problem. In this case, we can create a new TrustStore from the default one. By doing so, we make sure that the new TrustStore will include all of the initial CA certificates:

keytool -importkeystore -srckeystore cacerts -destkeystore new_trustStore.p12 -srcstoretype PKCS12 -deststoretype PKCS12

Then, we import the certificates we need into the newly created TrustStore:

keytool -import -alias SomeSelfSignedCertificate -keystore new_trustStore.p12 -file /path/to/certificate/to/add

We can modify the initial TrustStore (meaning the cacerts itself), which might be a viable option. Other applications that rely on this exact JDK installation are the only thing to consider. They will receive these newly added certificates into default cacerts as well. That could or could not be OK, depending on the requirements.

5. Programmatically Consider Both TrustStores

This approach is a bit more complicated than the one we described. The challenge is that in JDK, there are no built-in ways to ask TrustManager (the one that decides to trust somebody) to consider multiple TrustStores. So we would have to implement it ourselves.

The first thing to do is to get the instance of the TrustManagerFactory. When we have it, we’ll be able to get the TrustManager that we need:

TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init((KeyStore) null);

So here, we get the default TrustManagerFactory, and then we initialize it with null as an argument. The init method initializes the TrustManagerFactory with the given TrustStore. As a side note, Java KeyStore and TrustStore are both represented by the KeyStore Java class. So when we pass null as an argument, TrustManagerFactory would initialize itself with default TrustStore (cacerts).

Once we have that, we should get the actual TrustManager from TrustManagerFactory. More specifically, we need the X509TrustManager. This TrustManager is the one that is responsible for determining whether the given x509 Certificate should be trusted or not:

X509TrustManager defaultX509CertificateTrustManager = null;
for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) {
    if (trustManager instanceof X509TrustManager x509TrustManager) {
        defaultX509CertificateTrustManager = x509TrustManager;
        break;
    }
}

So, we have the default JDK’s X509TrustManager, which knows only about default cacerts. Now, we need to load our own TrustStore and initialize the new TrustManagerFactory with this new TrustStore of ours:

try (FileInputStream myKeys = new FileInputStream("new_TrustStore.p12")) {
    KeyStore myTrustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    myTrustStore.load(myKeys, "new_TrustStore_pwd".toCharArray());
    trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(myTrustStore);

    X509TrustManager myTrustManager = null;
    for (TrustManager tm : trustManagerFactory.getTrustManagers()) {
        if (tm instanceof X509TrustManager x509TrustManager) {
            myTrustManager = x509TrustManager;
            break;
        }
    }
}

As we can see, we have loaded our TrustStore into a new KeyStore object using the given password. Then we get yet another default TrustManagerFactory instance (getInstance() method always returns a new object) and initialize it with our TrustStore. Then, in the same way as above, we find the X509TrustManager, which considers our TrustStore now. Now, the only thing left is configuring SSLContext to use both X509TrustManager implementations – the default one and ours.

6. Reconfiguring SSLContext

Now, we need to teach the SSLContext to use our 2 X509TrustManagers. The problem is that we cannot pass them separately into SSLContext. That is because SSLContext, surprisingly, will use only the first X509TrustManager it finds and will ignore the rest. To overcome this, we need to create a single finalX509TrustManager that is a wrapper over our two X509TrustManagers:

X509TrustManager finalDefaultTm = defaultX509CertificateTrustManager;
X509TrustManager finalMyTm = myTrustManager;

X509TrustManager wrapper = new X509TrustManager() {
    private X509Certificate[] mergeCertificates() {
        ArrayList<X509Certificate> resultingCerts = new ArrayList<>();
        resultingCerts.addAll(Arrays.asList(finalDefaultTm.getAcceptedIssuers()));
        resultingCerts.addAll(Arrays.asList(finalMyTm.getAcceptedIssuers()));
        return resultingCerts.toArray(new X509Certificate[resultingCerts.size()]);
    }

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return mergeCertificates();
    }

    @Override
    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        try {
            finalMyTm.checkServerTrusted(chain, authType);
        } catch (CertificateException e) {
            finalDefaultTm.checkServerTrusted(chain, authType);
        }
    }

    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        finalDefaultTm.checkClientTrusted(mergeCertificates(), authType);
    }
};

And then initialize the TLS SSLContext with our wrapper:

SSLContext context = SSLContext.getInstance("TLS");
context.init(null, new TrustManager[] { wrapper }, null);
SSLContext.setDefault(context);

We’re also setting this SSLContext as a default one. This is just in case since most of the clients that want to establish a secure connection would use TLS SSLContext. This serves as a backup option, though. We’re finally done.

7. Conclusion

In this article, we explored the ways how to use certificates from different TrustStores in one Java application.

Unfortunately, in Java, if we specify the TrustStore location from the command line, this would instruct Java to use only the specified TrustStore. So our options are either to modify the default cacerts TrustStore file or create a brand new TrustStore file that would contain all required CA certificate entries. A more complex approach is to force SSLContext to consider both TrustStores programmatically.

Still, all of these options would work, and we should use the one that fits our requirements.

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 – LSS – NPI (cat=Security/Spring Security)
announcement - icon

I just announced the new Learn Spring Security course, including the full material focused on the new OAuth2 stack in Spring Security:

>> CHECK OUT THE COURSE

eBook Jackson – NPI EA – 3 (cat = Jackson)
1 Comment
Oldest
Newest
Inline Feedbacks
View all comments