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

When building a web application, we often need information about the devices and browsers accessing our application so that we can deliver optimized user experiences.

A user agent is a string that identifies the client making requests to our server. It contains information about the client device, operating system, browser, and more. It’s sent to the server through the User-Agent request header.

However, parsing user agent strings can be challenging due to their complex structure and varied nature. The Yauaa (Yet Another UserAgent Analyzer) library helps simplify this process when working in the Java ecosystem.

In this tutorial, we’ll explore how to leverage Yauaa in a Spring Boot application to parse user agent strings and implement device-specific routing.

2. Setting up the Project

Before we dive into the implementation, we’ll need to include an SDK dependency and configure our application correctly.

2.1. Dependencies

Let’s start by adding the yauaa dependency to our project’s pom.xml file:

<dependency>
    <groupId>nl.basjes.parse.useragent</groupId>
    <artifactId>yauaa</artifactId>
    <version>7.28.1</version>
</dependency>

This dependency provides us with the necessary classes to parse and analyze the user agent request header from our application.

2.2. Defining UserAgentAnalyzer Configuration Bean

Now that we’ve added the correct dependency, let’s define our UserAgentAnalyzer bean:

private static final int CACHE_SIZE = 1000;

@Bean
public UserAgentAnalyzer userAgentAnalyzer() {
    return UserAgentAnalyzer
      .newBuilder()
      .withCache(CACHE_SIZE)
      // ... other settings
      .build();
}

The UserAgentAnalyzer class is the main entry point for parsing user agent strings.

The UserAgentAnalyzer, by default, uses an in-memory cache with a size of 10000, but we can update it as required using the withCache() method as we’ve done in our example. Caching helps us improve performance by avoiding repeated parsing of the same user agent strings.

3. Exploring UserAgent Fields

Once we’ve defined our UserAgentAnalyzer bean, we can use it to parse a user agent string and get information about the client.

For our demonstration, let’s take the user agent of the device that’s being used to write this tutorial:

Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.6 Safari/605.1.15

Now, we’ll use our UserAgentAnalyzer bean to parse the above and extract all available fields:

UserAgent userAgent = userAgentAnalyzer.parse(USER_AGENT_STRING);
userAgent
  .getAvailableFieldNamesSorted()
  .forEach(fieldName -> {
      log.info("{}: {}", fieldName, userAgent.getValue(fieldName));
  });

Let’s take a look at the generated logs when we execute the above code:

com.baeldung.Application : DeviceClass: Desktop
com.baeldung.Application : DeviceName: Apple Macintosh
com.baeldung.Application : DeviceBrand: Apple
com.baeldung.Application : DeviceCpu: Intel
com.baeldung.Application : DeviceCpuBits: 64
com.baeldung.Application : OperatingSystemClass: Desktop
com.baeldung.Application : OperatingSystemName: Mac OS
com.baeldung.Application : OperatingSystemVersion: >=10.15.7
com.baeldung.Application : OperatingSystemVersionMajor: >=10.15
com.baeldung.Application : OperatingSystemNameVersion: Mac OS >=10.15.7
com.baeldung.Application : OperatingSystemNameVersionMajor: Mac OS >=10.15
com.baeldung.Application : LayoutEngineClass: Browser
com.baeldung.Application : LayoutEngineName: AppleWebKit
com.baeldung.Application : LayoutEngineVersion: 605.1.15
com.baeldung.Application : LayoutEngineVersionMajor: 605
com.baeldung.Application : LayoutEngineNameVersion: AppleWebKit 605.1.15
com.baeldung.Application : LayoutEngineNameVersionMajor: AppleWebKit 605
com.baeldung.Application : AgentClass: Browser
com.baeldung.Application : AgentName: Safari
com.baeldung.Application : AgentVersion: 17.6
com.baeldung.Application : AgentVersionMajor: 17
com.baeldung.Application : AgentNameVersion: Safari 17.6
com.baeldung.Application : AgentNameVersionMajor: Safari 17
com.baeldung.Application : AgentInformationEmail: Unknown
com.baeldung.Application : WebviewAppName: Unknown
com.baeldung.Application : WebviewAppVersion: ??
com.baeldung.Application : WebviewAppVersionMajor: ??
com.baeldung.Application : WebviewAppNameVersion: Unknown
com.baeldung.Application : WebviewAppNameVersionMajor: Unknown
com.baeldung.Application : NetworkType: Unknown

As we can see, the UserAgent class provides valuable information about the device, operating system, browser, and more. We can use these fields and make informed decisions as per our business requirements.

It’s also important to note that not all the fields are available for a given user agent string, which is evident by the Unknown and ?? values in the log statements. If we don’t want these unavailable values displayed, we can use the getCleanedAvailableFieldNamesSorted() method of the UserAgent class instead.

4. Implementing Device-Based Routing

Now that we’ve looked at the various fields available in the UserAgent class, let’s put this knowledge to use by implementing device-based routing in our application.

For our demonstration, we’ll assume a requirement to serve our application to mobile devices while restricting access to non-mobile devices. We can achieve this by inspecting the DeviceClass field of the user agent string.

First, let’s define a list of supported device classes that we’ll consider as mobile devices:

private static final List SUPPORTED_MOBILE_DEVICE_CLASSES = List.of("Mobile", "Tablet", "Phone");

Next, let’s create our controller method:

@GetMapping("/mobile/home")
public ModelAndView homePage(@RequestHeader(HttpHeaders.USER_AGENT) String userAgentString) {
    UserAgent userAgent = userAgentAnalyzer.parse(userAgentString);
    String deviceClass = userAgent.getValue(UserAgent.DEVICE_CLASS);
    boolean isMobileDevice = SUPPORTED_MOBILE_DEVICE_CLASSES.contains(deviceClass);

    if (isMobileDevice) {
        return new ModelAndView("/mobile-home");
    }
    return new ModelAndView("error/open-in-mobile", HttpStatus.FORBIDDEN);
}

In our method, we use the @RequestHeader to get the value of the user agent string, which we parse using our UserAgentAnalyzer bean. Then, we extract the DEVICE_CLASS field from the parsed UserAgent instance and check if it matches any of the supported mobile device classes.

If we identify that the incoming request has been made from a mobile device, we return the /mobile-home view. Otherwise, we return an error view with an HTTP status of Forbidden, indicating that the resource is only accessible from mobile devices.

5. Testing Device-Based Routing

Now that we’ve implemented device-based routing, let’s test it to ensure it works as expected using MockMvc:

private static final String SAFARI_MAC_OS_USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 14_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Safari/605.1.15";

mockMvc.perform(get("/mobile/home")
  .header("User-Agent", SAFARI_MAC_OS_USER_AGENT))
  .andExpect(view().name("error/open-in-mobile"))
  .andExpect(status().isForbidden());

We simulate a request with a Safari user agent string for macOS and invoke our /home endpoint. We verified that our error view was returned to the client with an HTTP status of 403 forbidden.

Similarly, let’s now invoke our endpoint with a mobile user agent:

private static final String SAFARI_IOS_USER_AGENT = "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1";

mockMvc.perform(get("/mobile/home")
  .header("User-Agent", SAFARI_IOS_USER_AGENT))
  .andExpect(view().name("/mobile-home"))
  .andExpect(status().isOk());

Here, we use a Safari user agent string for iOS and assert that the request is successfully completed with the correct view returned to the client.

6. Reducing Memory Footprint and Speeding up Execution

By default, Yauaa parses all available fields from the user agent string. However, if we only need a subset of fields in our application, we can specify them in our UserAgentAnalyzer bean:

UserAgentAnalyzer
  .newBuilder()
  .withField(UserAgent.DEVICE_CLASS)
  // ... other settings
  .build();

Here, we configure the UserAgentAnalyzer to only parse the DEVICE_CLASS field that we used in our device-based routing implementation.

We can chain multiple withField() methods together if we need to parse multiple fields. This approach is highly recommended as it helps reduce memory usage and improves performance.

7. Conclusion

In this article, we explored using Yauaa to parse and analyze user agent strings.

We walked through the necessary configuration, looked at the different fields we have access to, and implemented device-based routing in our application.

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

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

>> CHECK OUT THE COURSE

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