2014-11-01 50 views
1

我想弄清楚我在开发小型应用程序时遇到的一个小问题的解决方案。我试图传递在一个支持bean内创建的对象,然后使用在另一个支持bean内创建的相同对象。但是,我不想制作这些备用豆@SessionScoped,并且最好不要使用@ManagedBean,因为我正在为我的JavaEE应用程序使用CDIJSF:将一个对象从一个支持bean传递到另一个支持bean

有无论如何,我可以做到这一点使用CDI批注和注入一个支持豆到另一个,然后有能力访问先前创建的对象?

作为一个例子,请参考下面豆:上述豆内创建

@Named 
@ViewScoped 
public RegisterController implements Serializable { 

    User user = new User(); 

    // Getter and Setter methods which are populated by the JSF page 
} 

获取对象User和下面的控制器内使用它:

@Named 
@ViewScoped 
public PaymentController implements Serializable { 

    @Inject RegisterController registerController; // Injecting bean 

    registerController.getUser().getName(); //this is null when I try access the properties of the object 'User'. I am assuming this is because @ViewScoped annotated on the 'RegisterController' class? 

    // I would like to use the User object created in 'RegisterController' here an access properties etc... 
} 

我可以使用@Inject注解由CDI提供?

UPDATE

好了,我已经得到了上面的工作,当我注释RegisterControllerSessionScoped注释,但我不希望这个bean注释SessionScoped,我可能会遇到在轨道下进一步影响,比如字段的预填充等等......任何想法如何以任何其他方式实现这一点?

+0

@SalihErikci,'@ RequestScoped' CDI注解不起作用,因为Object必须持续更长的时间,然后再持续一个'HTTP Request'。 – Maff 2014-11-01 12:46:20

回答

2

那么,@ViewScoped太短,@SessionScoped太长。那么为什么不使用@ConversationScoped

请参阅here

+0

我已经使用CDI @ConversationScoped实现了这个功能。谢谢你的提示。 – Maff 2014-11-02 10:34:13

0

,你可以在这个RegistrationController使用:

FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("user", user); 

和PaymentController:

FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("user"); 

这是非常有用的,可以节省你在地图上想要的对象。

相关问题