Reputation: 1306
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
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
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
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