简体   繁体   中英

Reading Value from application.properties

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).

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");
    }

}

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM