7

I am trying to get value from a property file on spring boot. application.properties file is under resources folder, and its content;

TEST=someText

And the code is;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.PropertySource;

@SpringBootApplication
@PropertySource("classpath:application.properties")

public class Bb8Application {


    @Value("${TEST}")
    static String someString;

    public static void main(String[] args) {

        System.out.print(someString);

    }

}

I get NULL as a result instead of "someText". Is there something that I am missing?

Marek J
  • 1,364
  • 8
  • 18
  • 33
  • Possible duplicate of [Spring: How to inject a value to static field?](https://stackoverflow.com/questions/7253694/spring-how-to-inject-a-value-to-static-field) – Marek J Dec 28 '18 at 11:59
  • Did you make sure that the `application.properties` file is actually present on the classpath, i.e. it is bundled with the JAR when you execute it? – Rüdiger Herrmann Dec 28 '18 at 22:05

2 Answers2

7

Spring does not allow injecting to static fields. If you really want to use static variable you can try this workaround.

Community
  • 1
  • 1
Marek J
  • 1,364
  • 8
  • 18
  • 33
0

You can use @Value annotation for static fields.

@Component
public class MyClass {

   private static String MY_STATIC_FIELD;

   public MyClass(@Value("${TEST}") String input) {
      MY_STATIC_FIELD = input;
   }

}

more for information: https://www.baeldung.com/spring-inject-static-field

Oguzhan Cevik
  • 638
  • 8
  • 18