java - 属性上的 Spring @Autowired 和 @Value 不起作用

标签 java spring spring-boot dependency-injection property-injection

我想在属性上使用 @Value,但我总是得到 0(在 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 管理的,否则构造函数参数将不起作用。

有谁知道是什么导致了这种奇怪的行为?

最佳答案

字段注入(inject)是在构造对象之后完成的,因为显然容器不能设置不存在的属性。该字段将始终在构造函数中取消设置。

如果你想打印注入(inject)的值(或者做一些真正的初始化:)),你可以使用一个用@PostConstruct注解的方法,它会在注入(inject)过程之后执行。

@Component
public class FtpServer {

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

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

}

关于java - 属性上的 Spring @Autowired 和 @Value 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46035971/

相关文章:

java - 缓冲图像 : extract subimage with same data

java - IgniteCache 不调用 loadCache()

java - 单元测试模拟服务实现

java - restTemplate 删除与正文

java - 我面临 "java.lang.IllegalArgumentException: Can not set int field com.example.demo.model.Customer.customerId to java.util.LinkedHashMap"

spring - 以编程方式禁用 RabbitAutoConfiguration

java - 字节数组转十六进制(int 格式)

java - 逐行读取文本文件并将这些行插入到输出文件上的 -d= 序列之后

java - 为什么无法使用 Files.move() 在驱动器上移动非空目录?

spring - 我如何加密密码将其插入数据库并在比较后何时连接?