Spring Boot @Value Properties

user6641655 picture user6641655 · Aug 19, 2016 · Viewed 118.5k times · Source

I have a Spring Boot application and in one of the classes, I try to reference a property from the application.properties file using @Value. But, the property does not get resolved. I have looked at similar posts and tried following the suggestions, but that didn't help. The class is:

@Configuration
@ComponentScan
@EnableAutoConfiguration
public class PrintProperty {

  @Value("${file.directory}")
  private String fileDirectory;

  public void print() {
    System.out.println(fileDirectory);
  }
}

I have the property file.directory in application.properties. I have other fields as well.

Answer

牛向辉 picture 牛向辉 · Mar 28, 2017

I had the same problem like you. Here's my error code.

@Component
public class GetExprsAndEnvId {
    @Value("hello")
    private String Mysecret;


    public GetExprsAndEnvId() {
        System.out.println("construct");
    }


    public void print(){
        System.out.println(this.Mysecret);
    }


    public String getMysecret() {
        return Mysecret;
    }

    public void setMysecret(String mysecret) {
        Mysecret = mysecret;
    }
}

This is no problem like this, but we need to use it like this:

@Autowired
private GetExprsAndEnvId getExprsAndEnvId;

not like this:

getExprsAndEnvId = new GetExprsAndEnvId();

Here, the field annotated with @Value is null because Spring doesn't know about the copy of GetExprsAndEnvId that is created with new and didn't know to how to inject values in it.