Spring 属性 上的@Autowired 和@Value 不工作
Spring @Autowired and @Value on property not working
我想在 属性 上使用 @Value
,但我总是得到 0
(on int)。
但是在构造函数参数上它有效。
示例:
@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???
}
}
对象是 spring 托管的,否则构造函数参数将不起作用。
有谁知道导致这种奇怪行为的原因吗?
我认为问题是因为Spring的执行顺序:
首先,Spring调用构造函数创建一个实例,类似于:
FtpServer ftpServer=new FtpServer(<value>);
之后通过反射,填充属性:
code equivalent to ftpServer.setPort(<value>)
因此在构造函数执行期间属性仍然为 0,因为这是 int
.
的默认值
字段注入是在构造对象之后完成的,因为显然容器不能设置 属性 不存在的东西。该字段将始终在构造函数中取消设置。
如果你想打印注入的值(或者做一些真正的初始化:)),你可以使用注解为@PostConstruct
的方法,该方法将在注入过程之后执行。
@Component
public class FtpServer {
@Value("${ftp.port}")
private int port;
@PostConstruct
public void init() {
System.out.println(this.port);
}
}
这是会员注入:
@Value("${ftp.port}")
private int port;
spring 在从其构造函数实例化 bean 之后执行的操作。所以在 spring 从 class 实例化 bean 时,spring 没有注入值,这就是为什么你得到默认的 int 值 0.
确保在构造函数被 spring 调用后调用变量,以防您想坚持使用成员注入。
我想在 属性 上使用 @Value
,但我总是得到 0
(on int)。
但是在构造函数参数上它有效。
示例:
@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???
}
}
对象是 spring 托管的,否则构造函数参数将不起作用。
有谁知道导致这种奇怪行为的原因吗?
我认为问题是因为Spring的执行顺序:
首先,Spring调用构造函数创建一个实例,类似于:
FtpServer ftpServer=new FtpServer(<value>);
之后通过反射,填充属性:
code equivalent to ftpServer.setPort(<value>)
因此在构造函数执行期间属性仍然为 0,因为这是 int
.
字段注入是在构造对象之后完成的,因为显然容器不能设置 属性 不存在的东西。该字段将始终在构造函数中取消设置。
如果你想打印注入的值(或者做一些真正的初始化:)),你可以使用注解为@PostConstruct
的方法,该方法将在注入过程之后执行。
@Component
public class FtpServer {
@Value("${ftp.port}")
private int port;
@PostConstruct
public void init() {
System.out.println(this.port);
}
}
这是会员注入:
@Value("${ftp.port}")
private int port;
spring 在从其构造函数实例化 bean 之后执行的操作。所以在 spring 从 class 实例化 bean 时,spring 没有注入值,这就是为什么你得到默认的 int 值 0.
确保在构造函数被 spring 调用后调用变量,以防您想坚持使用成员注入。