In this post under Spring Core, I will show with example how to apply “@Value” annotation on a constructor parameter.
In my previous post under Spring Core, I have showed how to apply “@Value” annotation on class instance variable.
Below is the complete main class showing how to apply “@Value” annotation on a constructor parameter
Main class
package core.package39;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Configuration
@PropertySource("app1.properties")
public class Example39 {
private String name;
public Example39(@Value("${name}") String name) {
this.name = name;
}
public static void main(String[] args) {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Example39.class);
Example39 example39 = applicationContext.getBean(Example39.class);
System.out.println(example39.name);
}
}
In the above code, we have created a constructor for “Example39” class with one constructor parameter “name”.
To which we have applied the “@Value” annotation.
When the Spring framework creates an instance of “Example39” class by itself, it will inject the value of “name” property from “app1.properties” to constructor parameter “name”.
In this way, we can use “@Value” annotation on constructor parameter.