且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

来自另一个托管bean的托管bean的访问权限属性

更新时间:2021-10-23 01:54:16

无法在构造函数中访问注入的依赖项.您基本上希望Java能够执行以下操作:

It's not possible to access an injected dependency in the constructor. You're basically expecting that Java is able to do something like this:

SecondBean secondBean; // Declare.
secondBean.firstBean = new FirstBean(); // Inject.
secondBean = new SecondBean(); // Construct.

如果尚未构造实例,则绝对不可能设置实例变量.相反,它的工作方式如下:

It's absolutely not possible to set an instance variable if the instance is not constructed yet. Instead, it works as follows:

SecondBean secondBean; // Declare.
secondBean = new SecondBean(); // Construct.
secondBean.firstBean = new FirstBean(); // Inject.

然后,为了基于注入的依赖关系执行业务操作,请使用带有@PostConstruct注释的方法.构造依赖项注入后,依赖关系注入管理器将直接调用它.

Then, in order to perform business actions based on injected dependencies, use a method annotated with @PostConstruct. It will be invoked by the dependency injection manager directly after construction and dependency injection.

所以,只需替换

public SecondBean() {
    System.out.println(firstBean.getName());
}

作者

@PostConstruct
public void init() { // Note: method name is fully to your choice.
    System.out.println(firstBean.getName());
}