2013-03-15 78 views
0

我试图访问托管bean构造函数中的会话bean数据。为此,我使用下面的@ManagedProperty注释。当我尝试访问构造函数时,它会给出java.lang.NullPointerException,并且可以在另一个函数中访问同一段代码。可能是我需要为构造函数做一些不同的事情。有人能指导我需要做什么吗?在JSF托管bean的构造函数中访问会话bean数据

@ManagedProperty(value="#{sessionBean}") 
private SelectCriteriaBean sessionData; 

// This is contructor 
public ModifyBusinessProcessBean() { 
    logger.debug(getSessionData().getSelectedBusinessProcessLevelZero());  
} 

// Another Function where the same code doesn't give error 
public anotherFunction() { 
    logger.debug(getSessionData().getSelectedBusinessProcessLevelZero());  
} 

回答

3

您不应该在构造函数中使用@ManagedProperty,因为它尚未设置。当首先创建托管bean时,会调用其构造函数,然后使用setter设置托管属性。您应该使用与@PostConstruct标注的方法,因为它的属性被设置后调用:

@PostConstruct 
public void init() { 
    logger.debug(getSessionData().getSelectedBusinessProcessLevelZero()); 
} 
+0

哈!行动中的并发:) – skuntsel 2013-03-15 08:51:46

+0

是的,那真的是。 :) – partlov 2013-03-15 08:53:13

+0

+1输入速度:) – skuntsel 2013-03-15 08:55:18

3

这是预期的行为。

@PostConstruct方法在bean的构建和注入依赖项之后执行,例如@ManagedProperty已经发生。所以你的依赖不会在构造函数中可用。

你需要做注释的方法与@PostConstruct,并参阅你的依赖什么是标准方式:

@PostConstruct 
public void init() { 
    injectedDependency.performOperation(); 
}