Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Spring Boot won't pick up variable from application.yml

I am working on an application that uses a variable that is declared in the application.yml file. In my application.yml file it is defined as so:

lwt:
  application:
    five-minute-jobs: ${ENABLE_FIVE_MINUTE_JOBS:true}

In my controller file it is declared this way but it is always returning false whenever I log it in in the console. Here is the shortened version:

import org.springframework.beans.factory.annotation.Value;

public class EmailJobSchedulerController {

    @Value("${lwt.application.five-minute-jobs}")
    private boolean fiveMinuteJobsEnabled;

Am I declaring it correctly in the file? Been searching on other threads but haven't been able to find a clear answer for this. Thanks!

like image 647
BluePilot Avatar asked Oct 16 '25 15:10

BluePilot


2 Answers

May be you are not setting the env variable correctly. Can you do the following in your main @SpringBootApplication class and tell me what it is printing?

    @SpringBootApplication
    public class AccessingDataJpaApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(AccessingDataJpaApplication.class);
        System.out.println(context.getEnvironment().getProperty("ENABLE_FIVE_MINUTE_JOBS"));
        System.out.println(context.getEnvironment().getProperty("lwt.application.five-minute-jobs"));
    }

   }
like image 124
Kavithakaran Kanapathippillai Avatar answered Oct 18 '25 07:10

Kavithakaran Kanapathippillai


@value annotation will get the value if it's under bean life cycle else you need to take from ConfigureEnviornment class, is below code is registered with bean ? I feel you might be missed adding @RestController on top of this class

 import org.springframework.beans.factory.annotation.Value;
@RestController
 public class EmailJobSchedulerController {

@Value("${lwt.application.five-minute-jobs}")
private boolean fiveMinuteJobsEnabled;
like image 30
Pandit Biradar Avatar answered Oct 18 '25 06:10

Pandit Biradar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!