Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

What am I doing wrong?

>Solution :

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();
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading