Shehan Simen
Shehan Simen

Reputation: 1306

Read application.properties value from Spring boot main class

In my spring boot app, I have variable value set in application.properties. I want to read it in the main java class. How can I do that? following code returns null.

@SpringBootApplication
public class MyApplication {

@Value( "${spring.shutdown.sleep.time}" )
private static String shutdownSleepTime;

public static void main(String[] args) {
    ConfigurableApplicationContext applicationContext = SpringApplication.run(MysApplication.class, args);
    System.out.println("sleep time : " + shutdownSleepTime);

Upvotes: 0

Views: 3825

Answers (3)

Mark Bramnik
Mark Bramnik

Reputation: 42431

So you want to print something when the application context is created.

For that You can use event listeners:


@SpringBootApplication
public class MyApplication {

  @Value( "${spring.shutdown.sleep.time}" )
  private String shutdownSleepTime; // not static

  public static void main(String[] args) {
      ConfigurableApplicationContext applicationContext = 
  SpringApplication.run(MysApplication.class, args);

  }

  @EventListener
  public void onAppContextStarted(ApplicationStartedEvent e) {
      System.out.println("sleep time : " + shutdownSleepTime); 
  }
}

Upvotes: 0

Peter Lustig
Peter Lustig

Reputation: 1701

You can read the property from the applicationContext.

public static void main(String[] args) {
    ConfigurableApplicationContext applicationContext = SpringApplication.run(MysApplication.class, args);
    String shutdownSleepTime = applicationContext.getEnvironment().getProperty("spring.shutdown.sleep.time");
}

Upvotes: 2

yeahseol
yeahseol

Reputation: 385

I recommend it

@SpringBootApplication
public class MyApplication {

public static void main(String[] args) {
    ConfigurableApplicationContext applicationContext = SpringApplication.run(MysApplication.class, args);
}

@Component
public static class CmdRunner implement CommandLineRunner {

  @Value( "${spring.shutdown.sleep.time}" )
  private static String shutdownSleepTime;

  public void run(String... args) throws Exception {
    System.out.println("sleep time : " + shutdownSleepTime);
  }
}

Upvotes: 0

Related Questions