Search code examples
spring-bootapplication.properties

Losing Spring @Value("${}") when instantiate class


I'm using SpringBoot 2.1.3 (Embedded Tomcat) + Thymeleaf 3.0 + Java 8.

I have a simple class like this:

@Data
public class Machine {
   private Integer price;
   @Value("${settings.default}")
   private String settings;
}

And a simple application.properties:

settings.default=deafult

But when I instantiate the class anyway in the code:

Machine m = new Machine();
System.out.println(m.getSettings);

It returns null. Obviuosly if I do:

@Data
public class Machine {
   private Integer price;
   private String settings = "Default";
}

It works.. Or if I use that value inside a class method it works again. What's wrong? Can I do something like that?

Thank you


Solution

  • A class should be declared with stereotype annotations to use @Value

    @Component
    public class Machine {
       private Integer price;
       @Value("${settings.default}")  
       private String settings;
    }
    

    And of course you have to autowire the Machine class (Spring has defined the bean), instantiating a new Object will not get the value, so to use

    @Service
    public class FooService {
      @Autowire
      private Machine machine;
    
      public void fooMethod() {
        System.out.println(machine.getSettings()); // default
      }
    }