Inject CDI bean into JSF @ViewScoped bean

只愿长相守 提交于 2019-12-04 07:50:18
Tarik

First, If you are attempting to use CDI, you need to activate it by putting a WEB-INF/beans.xml file in your application (note that this file can be empty), more informations about that file could be found in the Weld - JSR-299 Reference Implementation.

As you are using Tomcat, please be sure to respect all the configuration requirements by following the steps in How to install CDI in Tomcat?

Second, Even if you can use @Inject inside a JSF managed bean, It's preferable that you don't mix JSF managed beans and CDI, please see BalusC's detailed answer regarding Viewscoped JSF and CDI bean.

So if you want to work only with CDI @Named beans, you can use OmniFaces own CDI compatible @ViewScoped:

import javax.inject.Named;
import org.omnifaces.cdi.ViewScoped;

@Named
@ViewScoped
public class SomeBean implements Serializable {

    @Inject
    ServiceBean serviceBean;
}

Or, if you want to work only with JSF managed beans, you can use @ManagedProperty to inject properties:

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

@ManagedBean
@ViewScoped
public class SomeBean{

@ManagedProperty(value = "#{serviceBean}")
ServiceBean serviceBean;

}

See also:

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