0

I am not familiar with Java Spring. I am trying to fix a small bug in a Spring Boot code another developer has written. I can't seem to find a proper way to read a value I newly defined in application.properties. However, the code uses other values defined in application.properties; only that, even if I use the same syntax the other developer has used, still I can't read the value.

Here's what I've already tried:

read from environment:

import org.springframework.core.env.Environment;

public class MyClass {
    String myVar;

    public MyClass(String a, boolean b, Environment environment) {
         this.myVar = environment.getProperty("property.to.read");
    }

}

@Value

@Autowired
public class MyClass {
    String myVar;

    public MyClass(String a, boolean b, @Value("${property.to.read}") String c) {
         this.myVar = c;
    }

}

On both these occasions, myVar end up reporting null. Is there another configuration like an XML entry I need to add to get this to work? I have no Spring knowledge (I am not an experienced Java developer also, only trying to fix a bug in the code).

c00der
  • 543
  • 1
  • 4
  • 20

2 Answers2

2

Try to Autowire the Environment and then fetch the property . I have just extended your example by adding the @Autowired dependency.

import org.springframework.core.env.Environment;

public class MyClass {
    String myVar;

@Autowired
private Environment env;

    public CalibrateJob(String a, boolean b) {
         this.myVar = env.getProperty("property.to.read");
    }

}
Dev-vruper
  • 421
  • 3
  • 12
  • Thanks, but I am getting a NullPointerException. Intellij complaints env is not initialized. Also, I am trying to use env in the constructor of the class. – c00der May 02 '21 at 22:28
  • Check this out once , it looks like its getting initialized early hence throwing nullpointer. https://stackoverflow.com/q/19454289/6309111 – Dev-vruper May 02 '21 at 22:50
0

Maybe you can try to declare the value like this. The "resource.path" is the key value inside the application.properties.

   @Value("${resource.path}")
        private String resourcePath;
lee yiyang
  • 75
  • 6