春天@Autowired和@Value属性不起作用

Jan*_*tze 6 java spring dependency-injection property-injection spring-boot

我想@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???
    }
}
Run Code Online (Sandbox Code Playgroud)

该对象是spring管理的,否则构造函数参数将不起作用.

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

Dan*_*ski 10

在构造对象之后进行场注入,因为很明显容器不能设置不存在的东西的属性.该字段将始终在构造函数中取消设置.

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

@Component
public class FtpServer {

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

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

}
Run Code Online (Sandbox Code Playgroud)

  • 我不知道@PostConstruct 注释...+1 我学到了一些新东西! (4认同)

Pab*_*ano 5

我认为问题是由于Spring的执行顺序引起的:

  • 首先,Spring调用构造函数来创建一个实例,如:

    FtpServer ftpServer=new FtpServer(<value>);

  • 之后,通过反射,属性被填充:

    code equivalent to ftpServer.setPort(<value>)

因此在构造函数执行期间,该属性仍为0,因为这是an的默认值int.