Mathias Hillmann
Mathias Hillmann

Reputation: 1837

Spring not injecting @value annotation in property

I have the following class:

@Component
public class Scheduler {

    @Value("${build.version}")
    private String buildVersion;

    public void test() {
         System.out.println(this.buildVersion);
    }

}

I am calling the method test() from a controller:

@RestController
public class ApiController {

    @GetMapping("/status")
    public StatusResponse status() {
        Scheduler scheduler = new Scheduler();
        scheduler.update();
    }

However spring is not injecting the build.version value even though the class has a @Component annotation.

I am using the same property in a controller and it works fine.

What am I doing wrong?

Upvotes: 0

Views: 129

Answers (2)

Bhanu
Bhanu

Reputation: 221

If you are using application.yml to provide value to these properties then use @ConfigurationProperties on top of the class. You do not need to give @Value on every property value, for example:

@Component
@Data
@ConfigurationProperties(prefix = "build")
public class SchedulerProperties {

    private String buildVersion;

}

In application.yml define as below

build:
  buildVersion: "XYZ"

Then you can just call version from the properties class

@Component
public class Scheduler {

   @Autowired
   private SchedulerProperties schedulerProperties;

    public void test() {
         System.out.println(schedulerProperties.getBuildVersion());
    }

}

Upvotes: 1

Tsvetoslav Tsvetkov
Tsvetoslav Tsvetkov

Reputation: 1176

Try out this way, as you create instance with new instead of rely on Spring object managing(Inversion of control)

@RestController
public class ApiController {


   private Scheduler scheduler;

   @Autowired
   public ApiController(Scheduler scheduler) {
      this.scheduler = scheduler 
   }

   @GetMapping("/status")
   public StatusResponse status() {
      scheduler.update();
  }
}

Upvotes: 1

Related Questions