Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot application to read a value from properties file in main method

I am trying to get the value of a property

hello.world=Hello World

in MainApp class

@SpringBootApplication
public class MainApp {
   public static void main(String[] args) {
      SpringApplication.run(MainApp.class, args);
}

This didn't work as its the main method.

@Value("${hello.world}")
public static String helloWorld;

Maybe its possible to load by

  Properties prop = new Properties();

    // load a properties file
    prop.load(new FileInputStream(filePath));

Is there any other better way to get the properties using Spring in the main method of SpringBoot before SpringApplication.run

like image 898
Cork Kochi Avatar asked Jan 08 '18 18:01

Cork Kochi


2 Answers

ConfigurableApplicationContext ctx = 
           SpringApplication.run(MainApp.class, args);
String str = ctx.getEnvironment().getProperty("some.prop");
System.out.println("=>>>> " + str);
like image 135
sanit Avatar answered Oct 06 '22 08:10

sanit


You have declared the variable helloWorld as static. Hence you need to use Setter Injection and not Field Injection.

Injecting a static non-final field is a bad practice. Hence Spring doesn't allow it. But you can do a workaround like this.

public static String helloWorld;

      @Value("${hello.world}")
        public void setHelloWorld(String someStr) {
          helloWorld = someStr
        }

You can access this variable helloWorld at any point in the class, if its any other class. But if you want to do it in the main class. You can access the variable only after this line

SpringApplication.run(MainApp.class, args);)

i.e only after the application has started.

like image 31
pvpkiran Avatar answered Oct 06 '22 08:10

pvpkiran