This question already has an answer here:
这个问题在这里已有答案:
- NullPointerException while trying to access @Inject bean in constructor 2 answers
尝试在构造函数2中访问@Inject bean时出现NullPointerException
This is my SessionScoped managed bean :
这是我的SessionScoped托管bean:
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
@Named("clientSessionBean")
@SessionScoped
public class ClientSessionManagedBean implements Serializable {
...
}
This is my requestscoped managed bean
这是我的requestcoped托管bean
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.inject.Named;
@Named("myBean")
@RequestScoped
public class MyManagedBean {
@Inject
private ClientSessionManagedBean clientSessionBean;
..
}
The value clientSessionBean
giving me null
.
值clientSessionBean给我null。
How can I inject a sessionScoped bean in a requestscoped managed bean ?
如何在requestcoped托管bean中注入sessionScoped bean?
Is there any problem with the package ?
包裹有问题吗?
1 个解决方案
#1
Injected resources are available only after the constructor has run, i.e. during @PostConstruct
and beyond. From the spec docs for JSR-250:
注入的资源仅在构造函数运行后才可用,即在@PostConstruct及更高版本期间。来自JSR-250的规范文档:
The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization
PostConstruct注释用于在完成依赖项注入以执行任何初始化之后需要执行的方法
As you should be able to infer from the excerpt above, the sequence of events in the lifecycle of a bean is:
正如您应该能够从上面的摘录中推断出,bean生命周期中的事件序列是:
-
Initialization i.e. calling the constructor (the actual mechanism is more complex, but it boils down to this)
初始化即调用构造函数(实际机制更复杂,但归结为此)
Performing injections
-
Call lifecycle callback, i.e.
@PostConstruct
. It's at this point, that you're allowed to make use of anything that was created in #2调用生命周期回调,即@PostConstruct。在这一点上,你被允许使用在#2中创建的任何东西
Related
- Why use @PostConstruct?
- Initialization of List in a JSF Managed bean (point #3)
为什么要使用@PostConstruct?
在JSF托管bean中初始化List(第3点)
#1
Injected resources are available only after the constructor has run, i.e. during @PostConstruct
and beyond. From the spec docs for JSR-250:
注入的资源仅在构造函数运行后才可用,即在@PostConstruct及更高版本期间。来自JSR-250的规范文档:
The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization
PostConstruct注释用于在完成依赖项注入以执行任何初始化之后需要执行的方法
As you should be able to infer from the excerpt above, the sequence of events in the lifecycle of a bean is:
正如您应该能够从上面的摘录中推断出,bean生命周期中的事件序列是:
-
Initialization i.e. calling the constructor (the actual mechanism is more complex, but it boils down to this)
初始化即调用构造函数(实际机制更复杂,但归结为此)
Performing injections
-
Call lifecycle callback, i.e.
@PostConstruct
. It's at this point, that you're allowed to make use of anything that was created in #2调用生命周期回调,即@PostConstruct。在这一点上,你被允许使用在#2中创建的任何东西
Related
- Why use @PostConstruct?
- Initialization of List in a JSF Managed bean (point #3)
为什么要使用@PostConstruct?
在JSF托管bean中初始化List(第3点)