Understanding @Value, @ConfigurationProperties, and @PropertySource in Spring Boot

Understanding @Value, @Configuration Properties, and @PropertySource in Spring Boot

When working with Spring Boot applications, external configuration is key to building flexible and maintainable software. Instead of hardcoding values, Spring provides annotations to inject configuration from .properties or .yml files. The three most commonly used annotations are:

  • @Value

  • @ConfigurationProperties

  • @PropertySource

In this blog, we’ll break down their purpose, usage, and best practices with examples.


 @Value Annotation

Purpose:  Inject a single property from application.properties or application.yml into a Spring Bean’s instance variable

Syntax:

@Value("${employee.name}")
private String name;


In application.properties

employee.name=SriPriya

 

c

@ConfigurationProperties Annotation

 

  • Purpose: Bind a group of related properties into a single POJO (Plain Old Java Object).

public class Billing {
    public static void main(String[] args) {
        IPayment payment = new CardPayment();
        payment.pay(2000);
        payment.printReceipt();

        payment = new UpiPayment();
        payment.pay(1500);
        payment.printReceipt();
    }
}

Output:

Payment using Card: 2000
Card Statement for September
Payment using UPI: 1500
Printing receipt...

What are Static Methods ?

Static methods in interfaces are:

– Declared using the `static` keyword.
– Belong to the interface itself (not to instances).
– Cannot be overridden.
– Must be called using the interface name.

Example:

interface IPayment {
    static void showDetails() {
        System.out.println("Payment process for billing.");
    }
}

Usage:

public class Billing {
    public static void main(String[] args) {
        IPayment.showDetails();
    }
}

Difference Between Default and Static Methods

Feature Default Static
Keyword Used default static
Belongs To Implementation class obj Interface
Overridable? Yes No
called using implementation class obj Interface name
Purpose Add new functionality without breaking contract Common functionality across all implementation classes

Real-world Example – Comparator Interface

The Comparator interface in Java makes heavy use of default and static methods:

– Default methods: reversed(), thenComparing()
– Static methods: naturalOrder(), reverseOrder()

This shows how Java uses these methods to enhance old interfaces without breaking existing code.

Conclusion

– Use default methods when you want to add functionality and still give implementing classes the choice to override.
– Use static methods when you want to provide utility-like, common behavior shared across all classes.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top