DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Testcontainers With Kotlin and Spring Data R2DBC
  • Exploring Apache Ignite With Spring Boot
  • Commonly Occurring Errors in Microsoft Graph Integrations and How To Troubleshoot Them (Part 4)
  • Implementing Infinite Scroll in jOOQ

Trending

  • AI-Based Threat Detection in Cloud Security
  • How Kubernetes Cluster Sizing Affects Performance and Cost Efficiency in Cloud Deployments
  • Mastering Advanced Traffic Management in Multi-Cloud Kubernetes: Scaling With Multiple Istio Ingress Gateways
  • Mastering Fluent Bit: Installing and Configuring Fluent Bit on Kubernetes (Part 3)
  1. DZone
  2. Coding
  3. Frameworks
  4. Validating Configuration Properties in Spring Boot Application Startup

Validating Configuration Properties in Spring Boot Application Startup

This step-by-step guide explains validating Configuration Properties in Spring Boot application startup.

By 
Nilanchala Panigrahy user avatar
Nilanchala Panigrahy
·
May. 09, 24 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
2.5K Views

Join the DZone community and get the full member experience.

Join For Free

The @ConfigurationProperties annotation in Spring Boot is used to bind configuration parameters typically from properties or YAML files to a Java class. But, did you know you also can validate configuration properties at spring application startup with @ConfigurationProperties annotation? Let's dive in!

Tutorial

Let's say we have a Spring Boot importer service that periodically imports customer data from a CSV file to the database. For the importer to work, we have the following configurations:

YAML
 
importer:  
  service:  
    filePath: '/nfs/files'
    fileType: '.xslx'
    threadPoolSize: 3


These properties can be mapped to a Java class automatically using @ConfigurationProperties annotation as follows:

Java
 
@Getter 
@Setter
@Component
@ConfigurationProperties(prefix = "importer.service")
public class ImporterConfig {  
    String filePath;
    String fileType;
    int threadPoolSize;
}


Now, let's say we want to ensure the importer configuration is provided and meets the validation criteria when the application starts. If any of the validation fails, then the application should fail during startup.

For this validation to work, we need to have a JSR-380 implementation like Hibernate Validator on your classpath.

implementation 'org.springframework.boot:spring-boot-starter-validation'


Once we have a validator in the classpath, we need to explicitly enable the configuration properties validation using @Validated annotation.

For example:

Java
 
@Getter  
@Setter  
@Component  
@Validated  
@ConfigurationProperties(prefix = "importer.service")  
public class ImporterConfig {  

    @NotNull  
    String filePath;  

    @NotNull  
    @Pattern(regexp = "\\.csv$|\\.txt$")  
    String fileType;  

    @Positive  
    @Max(10)  
    int threadPoolSize;  
}


This can validate properties on application startup when used in conjunction with JSR-380 bean validation annotations such as @Max and @NotNull. Here are some of the common annotations used for bean validation:

  • @NotNull: Specifies that a property must not be null
  • @NotEmpty: Specifies that a property must be not null or not empty
  • @Size: Ensure that a property size is between attributes min and max
  • @Email: Specifies that a property must be a valid email address
  • @AssertTrue/@AssertFalse: Ensure that a property value is true/false
  • @Positive/@Negative: Ensure that a property is positive/negative
  • @Past/@Future: Specifies that the date must be in the past/future
  • @Max/@Min: Specifies that a property has a value not greater/not smaller than the value attribute

A full list of built-in validation constraints in JSR 380 can be found here.

Now, run the application and notice that it will bind these properties application.yaml to the ImporterConfig object and validate them at application startup, thus ensuring the application doesn't run with invalid configurations.

If the validation fails, it will result in BindException as shown below:

***************************
APPLICATION FAILED TO START
***************************

Description:

Binding to target com.stacktips.app.config.ImporterConfig failed:

    Property: importer.service.fileType
    Value: ".xlsx"
    Origin: class path resource [application.yaml] - 8:15
    Reason: must match "\.csv$|\.txt$"


Action:

Update your application's configuration


Now you update the fileType: .csv and the application will start as expected.

Considerations for Using Records

Starting with Spring Boot 2.6 and Java 16, you can use record classes with @ConfigurationProperties. But there are a few things you need to consider when using records.

Java
 
@Validated  
@ConfigurationProperties(prefix = "importer.service")  
public record ImporterProperties(  
        @NotNull String filePath,  
        @Min(3) int threadPoolSize) {  
}


The @Componenet annotation cannot be used with records. Your IDE will show annotated with @ConstructorBinding but defined as a Spring component an error.

This is because the @Component annotation is generally used to define a bean that the Spring container will automatically detect and manage. As Java records are immutable, it conflicts with the way Spring manages beans, which involves proxying, intercepting, and potentially altering object states or behavior.

To fix this, we need to remove the @Component annotation and explicitly define the bean registration. We can either use @EnableConfigurationProperties or define @Bean annotation in one of the @Configuration classes.

For example:

Java
 
@EnableConfigurationProperties(ImporterProperties.class)  
@SpringBootApplication  
public class MyApplication {  

    public static void main(String[] args) {  
       SpringApplication.run(MyApplication.class, args);  
    }  

}


Video


Annotation Java (programming language) Property (programming) Spring Boot Data Types

Published at DZone with permission of Nilanchala Panigrahy, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Testcontainers With Kotlin and Spring Data R2DBC
  • Exploring Apache Ignite With Spring Boot
  • Commonly Occurring Errors in Microsoft Graph Integrations and How To Troubleshoot Them (Part 4)
  • Implementing Infinite Scroll in jOOQ

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!