Spring @Autowired and @Value on property not working

。_饼干妹妹 提交于 2019-12-05 07:44:56

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

}

I think the problem is caused because Spring's order of execution:

  • Firstly, Spring calls the constructor to create an instance, something like:

    FtpServer ftpServer=new FtpServer(<value>);

  • after that, by reflection, the attribute is filled:

    code equivalent to ftpServer.setPort(<value>)

So during the constructor execution the attribute is still 0 because that's the default value of an int.

This is a member injection:

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

Which spring does after instantiating the bean from its constructor. So at the time spring is instantiating the bean from the class, spring has not injected the value, thats why you are getting the default int value 0.

Make sure to call the variable after the constructor have been called by spring, in case you want to stick with member injection.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!