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’ll show how to use the Kubernetes API from Java applications using its official client library.

2. Why Use the Kubernetes API?

Nowadays, it is safe to say that Kubernetes became the de facto standard for managing containerized applications. It offers a rich API that allows us to deploy, scale and monitor applications and associated resources, such as storage, secrets, and environment variables. In fact, one way to think about this API is the distributed analog of the system calls available in a regular operating system.

Most of the time, our applications can ignore the fact that they’re running under Kubernetes. This is a good thing, as it allows us to develop them locally and, with a few commands and YAML incantations, quickly deploy them to multiple cloud providers with just minor changes.

However, there are some interesting use cases where we need to talk to the Kubernetes API to achieve specific functionality:

  • Start an external program to perform some task and, later on, retrieve its completion status
  • Dynamically create/modify some service in response to some customer request
  • Create a custom monitoring dashboard for a solution running across multiple Kubernetes clusters, even across cloud providers

Granted, those use-cases are not that common but, thanks to its API, we’ll see that they’re quite straightforward to achieve.

Furthermore, since the Kubernetes API is an open specification, we can be quite confident that our code will run without any modifications on any certified implementation.

3. Local Development Environment

The very first thing we need to do before we move on to create an application is to get access to a functioning Kubernetes cluster. While we can either use a public cloud provider for this, a local environment usually provides more control on all the aspects of its setup.

There are a few lightweight distributions that are suitable for this task:

The actual setup steps are beyond the scope of this article but, whatever option you choose, just make sure kubectl runs fine before starting any development.

4. Maven Dependencies

First, let’s add the Kubernetes Java API dependency to our project’s pom.xml:

<dependency>
    <groupId>io.kubernetes</groupId>
    <artifactId>client-java</artifactId>
    <version>11.0.0</version>
</dependency>

The latest version of client-java can be downloaded from Maven Central.

5. Hello, Kubernetes

Now, let’s create a very simple Kubernetes application that will list the available nodes, along with some information about them.

Despite its simplicity, this application illustrates the necessary steps we must go through to connect to a running cluster and perform an API call. Regardless of which API we use in a real application, those steps will always be the same.

5.1. ApiClient Initialization

The ApiClient class one of the most important classes in the API since it contains all the logic to perform a call to the Kubernetes API server. The recommended way to create an instance of this class is using one of the available static methods from the Config class. In particular, the easiest way of doing that is using the defaultClient() method:

ApiClient client = Config.defaultClient();

Using this method ensures that our code will work both remotely and in-cluster scenarios. Also, it will automatically follow the same steps used by the kubectl utility to locate the configuration file

  • Config file defined by KUBECONFIG environment variable
  • $HOME/.kube/config file
  • Service account token under /var/run/secrets/kubernetes.io/serviceaccount
  • Direct access to http://localhost:8080

The third step is the one that makes it possible for our app to run inside the cluster as part of any pod, as long the appropriate service account is made available to it.

Also, notice that if we have multiple contexts defined in the config file, this procedure will pick the “current” context, as defined using the kubectl config set-context command.

5.2. Creating an API Stub

Once we’ve got hold of an ApiClient instance, we can use it to create a stub for any of the available APIs. In our case, we’ll use the CoreV1Api class, which contains the method we need to list the available nodes:

CoreV1Api api = new CoreV1Api(client);

Here, we’re using the already existing ApiClient to create the API stub.

Notice that there’s also a no-args constructor available, but in general, we should refrain from using it. The reasoning for not using it is the fact that, internally, it will use a global ApiClient that must be previously set through Configuration.setDefaultApiClient(). This creates an implicit dependency on someone calling this method before using the stub, which, in turn, may lead to runtime errors and maintenance issues.

A better approach is to use any dependency injection framework to do this initial wiring, injecting the resulting stub wherever needed.

5.3. Calling a Kubernetes API

Finally, let’s get into the actual API call that returns the available nodes. The CoreApiV1 stub has a method that does precisely this, so this becomes trivial:

V1NodeList nodeList = api.listNode(null, null, null, null, null, null, null, null, 10, false);
nodeList.getItems()
  .stream()
  .forEach((node) -> System.out.println(node));

In our example, we pass null for most of the method’s parameters, as they’re optional. The last two parameters are relevant for all listXXX calls, as they specify the call timeout and whether this is a Watch call or not. Checking the method’s signature reveals the remaining arguments:

public V1NodeList listNode(
  String pretty,
  Boolean allowWatchBookmarks,
  String _continue,
  String fieldSelector,
  String labelSelector,
  Integer limit,
  String resourceVersion,
  String resourceVersionMatch,
  Integer timeoutSeconds,
  Boolean watch) {
    // ... method implementation
}

For this quick intro, we’ll just ignore the paging, watch and filter arguments. The return value, in this case, is a POJO with a Java representation of the returned document. For this API call, the document contains a list of V1Node objects with several pieces of information about each node. Here’s a typical output produced on the console by this code:

class V1Node {
    metadata: class V1ObjectMeta {
        labels: {
            beta.kubernetes.io/arch=amd64,
            beta.kubernetes.io/instance-type=k3s,
            // ... other labels omitted
        }
        name: rancher-template
        resourceVersion: 29218
        selfLink: null
        uid: ac21e09b-e3be-49c3-9e3a-a9567b5c2836
    }
    // ... many fields omitted
    status: class V1NodeStatus {
        addresses: [class V1NodeAddress {
            address: 192.168.71.134
            type: InternalIP
        }, class V1NodeAddress {
            address: rancher-template
            type: Hostname
        }]
        allocatable: {
            cpu=Quantity{number=1, format=DECIMAL_SI},
            ephemeral-storage=Quantity{number=18945365592, format=DECIMAL_SI},
            hugepages-1Gi=Quantity{number=0, format=DECIMAL_SI},
            hugepages-2Mi=Quantity{number=0, format=DECIMAL_SI},
            memory=Quantity{number=8340054016, format=BINARY_SI}, 
            pods=Quantity{number=110, format=DECIMAL_SI}
        }
        capacity: {
            cpu=Quantity{number=1, format=DECIMAL_SI},
            ephemeral-storage=Quantity{number=19942490112, format=BINARY_SI}, 
            hugepages-1Gi=Quantity{number=0, format=DECIMAL_SI}, 
            hugepages-2Mi=Quantity{number=0, format=DECIMAL_SI}, 
            memory=Quantity{number=8340054016, format=BINARY_SI}, 
            pods=Quantity{number=110, format=DECIMAL_SI}}
        conditions: [
            // ... node conditions omitted
        ]
        nodeInfo: class V1NodeSystemInfo {
            architecture: amd64
            kernelVersion: 4.15.0-135-generic
            kubeProxyVersion: v1.20.2+k3s1
            kubeletVersion: v1.20.2+k3s1
            operatingSystem: linux
            osImage: Ubuntu 18.04.5 LTS
            // ... more fields omitted
        }
    }
}

As we can see, there’s quite a lot of information available. For comparison, this is the equivalent kubectl output with default settings:

root@rancher-template:~# kubectl get nodes
NAME               STATUS   ROLES                  AGE   VERSION
rancher-template   Ready    control-plane,master   24h   v1.20.2+k3s1

6. Conclusion

In this article, we’ve presented a quick intro to the Kubernetes API for Java. In future articles, we’ll dig deeper into this API and explore some of its additional features:

  • Explain the difference between the available API call variants
  • Using Watch to monitor cluster events in realtime
  • How to use paging to efficiently retrieve a large volume of data from a cluster
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.

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