Home > database >  How to get spring @Value annotated values injected even before calling the constructor?
How to get spring @Value annotated values injected even before calling the constructor?

Time:11-29

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;
  }
  

}

CodePudding user response:

@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.

  1. An object is created but not initialised.
  2. The constructor is called, passing the object as this
  3. The object is fully constructed/created when the constructor returns.
  • Related