Injecting Beans in JSF 2.0

馋奶兔 提交于 2019-11-29 02:33:46
kolossus

You can't mix annotations from those two packages you're using javax.faces.bean.SessionScoped for JSF, and import javax.inject.Named for CDI. Both reflect different injection mechanisms and cannot be mixed on the same bean. You have to pick both annotations(for Injection and Bean Scoping) from the same package. Use the following sets from their corresponding packages

For CDI-based bean definitions

javax.enterprise.context.SessionScoped //for bean scoping
javax.inject.Named //for bean declaration
javax.inject.Inject //for injection

For JSF-based bean definitions

javax.faces.bean.SessionScoped //for bean scoping
javax.faces.bean.ManagedBean //for bean declaration
javax.faces.bean.ManagedProperty //for bean injection

EDIT: Now I understand your requirements better, use the following construct to inject a JSF managed bean

 @ManagedProperty(value="#{yourBeanName}")
 SessionBean yourSessionBean;

Also note that within JSF, you can inject only beans of a wider scope than their targets e.g. you can inject a @SessionScoped bean into a @RequestScoped bean and not the other way around

But since JSF managed beans are deprecated, better to use the CDI managed ones. In that case you can inject shorter scoped beans in wider scoped ones

Karl Kildén

Forget about managed beans. It won't work with a Filter that way. If you insist on using it then do it properly by follow the answer provided here:

How implement a login filter in JSF?

Now regarding CDI, if you problem is that a specific value is null and you have verified this by actually getting a NPE or so (Since for example Eclipse debugger sometimes get's it wrong). Then double check that you used correct SessionScoped like described by kolossus and also check what BalusC said (beans.xml).

A good way to see if CDI is working is to ask the manager for the bean. Put this debug code somewhere and try it:

@Inject
BeanManager manager;

@PostConstruct
private void test() {
    Bean<?> bean = (Bean) manager.resolve(manager.getBeans("ANY_NAMED_BEAN_EL_NAME"));
        System.out.println(bean);

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