Spring @Autowired和属性上的@Value不起作用 [英] Spring @Autowired and @Value on property not working

查看:378
本文介绍了Spring @Autowired和属性上的@Value不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在属性上使用 @Value ,但是我总是得到 0 (在int上)。< br>
但可以在构造函数参数上使用。

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

示例:

@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?

推荐答案

在构造对象之后进行字段注入,因为显然容器无法设置不存在的属性。

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.

如果要打印注入的值(或执行一些实际的初始化:)),则可以使用带有以下注释的方法: @PostConstruct ,将在注入过程之后执行。

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);
    }

}

这篇关于Spring @Autowired和属性上的@Value不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆