0

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?

6
  • Everything is correct in the definition. I also tried it out just in case and it works. I used the .properties file. You need to post more code in order to help you more Commented Jun 22, 2022 at 14:42
  • How is Scheduler used, and where is #test() being called? Commented Jun 22, 2022 at 14:43
  • You must @Autowired Scheduler, not create an instance with new, as Spring takes cares of the class managing Commented Jun 22, 2022 at 14:50
  • Why not autowiring Scheduler class instead of creating new? Commented Jun 22, 2022 at 14:52
  • I am not sure what @Autowired means Commented Jun 22, 2022 at 14:54

2 Answers 2

1

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();
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

}

1 Comment

I am not using any application.yml, just spring's magic.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.