Referencing Values from Properties File in Components
Properties File (
application.properties)
# Define properties
bookstore.name=My Awesome Bookstore
bookstore.location=Main Street, SpringfieldSpring Component
@Component
public class BookstoreProperties {
@Value("${bookstore.name}")
private String name;
@Value("${bookstore.location}")
private String location;
// getters and setters
public void printBookstoreDetails() {
System.out.println("Bookstore Name: " + name);
System.out.println("Bookstore Location: " + location);
}
}In Spring Boot applications, you can easily externalize configuration and access properties in your components. The above code demonstrates how you can define properties in the application.properties file and inject them into your Spring components using the @Value annotation.
Explanation:
Properties File (
application.properties):Contains key-value pairs defining properties and their values.
bookstore.nameandbookstore.locationare the properties used in this example.
Spring Component (
BookstoreProperties):Annotated with
@Component, making it a Spring-managed bean.Uses the
@Valueannotation to inject property values from theapplication.propertiesfile.The syntax
${property.name}within@Valuespecifies the property to be injected.printBookstoreDetailsis a method to display the injected values, demonstrating that the values have been successfully injected.
Benefits:
Decoupling of Configuration and Code: Enables changing the application's behavior without code changes by modifying the properties file.
Ease of Maintenance: Centralizes configuration management, simplifying changes and management.
Flexibility for Different Environments: Allows for different configurations in development, testing, and production environments without changing the codebase.
By leveraging the @Value annotation in Spring Boot, you can maintain clean separation between your configuration and code, making your application more adaptable and easier to manage across different environments.
Last updated