Jan Wytze :
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?
Daniel Olszewski :
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);
}
}
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=439215&siteId=1