Issue
In spring wiring is there a way to get the properties defined in application.properties to be wired to the corresponding field annotated with @Value before the constructor call.
Please see my comment in below code. I want the field prop1
(with its value) to be available to the constructor
. Is it possible. Similarly I want the field prop1
(with its value) to be available to the getInstanceProp()
method. Is it possible??
package com.demo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class WirableComponent {
@Value("${prop1}")
String prop1;
String instanceProp = getInstanceProp(); //null - I want prop1 value to be injected before making this method call so i can use it in the method.
public WirableComponent() {
System.err.println("no-args WirableComponent Constructor invoked");
System.err.println("value prop1: " + prop1); //null - I want prop1 value to be injected before constructor call so i can use it in constructor.
System.err.println("value instanceProp: " + instanceProp); //null
}
public String getInstanceProp() {
System.err.println("value prop1: " + prop1);
return null;
}
}
Solution
@value works like dependency injection rules of spring, when the application context loads and the bean for the WirableComponent class is created the prop1 value is can be instantiated through constructor injection(this can be used for the method call)
eg
@Component
public class WirableComponent {
private final String prop1;
public WirableComponent(@Value("${prop1}") String prop1){
this.prop1 = prop1;
}
}
Secondly although prop1 is a string literal, it takes value from spring context ,hence it cannot be available in the class until the constructor call happens as in Java:
At the byte code level.
- An object is created but not initialised.
- The constructor is called, passing the object as this
- The object is fully constructed/created when the constructor returns.
Answered By - Deb Das
Answer Checked By - Candace Johnson (JavaFixing Volunteer)