Spring @Autowired and @Value on property not working

Jan Wytze picture Jan Wytze · Sep 4, 2017 · Viewed 8.6k times · Source

I would like to use @Value on a property but I always get 0(on int).
But on a constructor parameter it works.

Example:

@Component
public class FtpServer {

    @Value("${ftp.port}")
    private int port;

    public FtpServer(@Value("${ftp.port}") int port) {
        System.out.println(port); // 21, loaded from the application.properties.
        System.out.println(this.port); // 0???
    }
}

The object is spring managed, else the constructor parameter wouldn't work.

Does anyone know what causes this weird behaviour?

Answer

Daniel Olszewski picture Daniel Olszewski · Sep 4, 2017

Field injection is done after objects are constructed since obviously the container cannot set a property of something which doesn't exist. The field will be always unset in the constructor.

If you want to print the injected value (or do some real initialization :)), you can use a method annotated with @PostConstruct, which will be executed after the injection process.

@Component
public class FtpServer {

    @Value("${ftp.port}")
    private int port;

    @PostConstruct
    public void init() {
        System.out.println(this.port);
    }

}