In previous tutorials we saw different ways to access properties provided by Environment . In this tutorial we will see how to use @Value annotation to access individual properties without using Environment.
Definition of Value(Version: spring-framework 6.1.2) package org.springframework.beans.factory.annotation;
........
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Value {
String value(); 1
}
Example
External Property File
src/main/resources/app.propertiescontact-person=Monica J. Pace
Using @Value
package com.logicbig.example;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import jakarta.annotation.PostConstruct;
@Component
public class MyBean {
@Value("${java.io.tmpdir:/temp}")
private String tempDir;
@Value("${contact-person:Joe}")
private String contactPerson;
@PostConstruct
public void postInit() {
System.out.println("System tempDir: " + tempDir);
System.out.println("contact-person: " + contactPerson);
}
}
It is possible to provide a default value after colon as seen above ('Joe' is the default value for contact person). So if a property (contact-person in our example) cannot be found the default value will be use at the injection point.
Java Config and main method
package com.logicbig.example;
import org.springframework.context.annotation.*;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
@Configuration
@PropertySource("classpath:app.properties")
@ComponentScan
public class UserPropertySourceExample {
@Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
public static void main(String[] args) {
new AnnotationConfigApplicationContext(UserPropertySourceExample.class);
}
}
OutputSystem tempDir: C:\Users\Joe\AppData\Local\Temp\ contact-person: Monica J. Pace
As seen in above class, we also have to register PropertySourcesPlaceholderConfigurer as a bean for @Value annotation to work.
Example ProjectDependencies and Technologies Used: - spring-context 6.1.2 (Spring Context)
Version Compatibility: 3.2.9.RELEASE - 6.1.2 Version compatibilities of spring-context with this example: Versions in green have been tested.
- jakarta.jakartaee-api 10.0.0 (Eclipse Foundation)
- JDK 17
- Maven 3.8.1
|