CDI Replacement for @ManagedProperty

微笑、不失礼 提交于 2019-12-06 02:03:49

问题


I'm very new to both CDI and JSF, and I'm trying to convert some code from Richfaces 4 showcase to use CDI instead of JSF annotations.

I understand that I can use @Named to replace @MangedBean and @Inject to replace @ManagedProperty. But I'm having some trouble. I'm trying to convert the Richfaces Tree example specifically.

I have made the following changes and I know this is not correct so please don't use this:

//@ManagedBean
//@ViewScoped
@Named
@SessionScoped
public class TreeBean implements Serializable {
    private static final long serialVersionUID = 1L;
//    @ManagedProperty(value = "#{cdsParser.cdsList}")
//    private List<CDXmlDescriptor> cdXmlDescriptors;
    @Inject
    private Instance<CDXmlDescriptor> cdXmlDescriptors;
// I also Tried :
//  @Inject
//    private CDParser cdsParser;
//    private List<CDXmlDescriptor> cdXmlDescriptors = cdsParser.getCdsList();

........

Then I added (and I'm not sure this is needed):

@Named
@SessionScoped
public class CDXmlDescriptor implements Serializable { ...

and changed:

//@ManagedBean(name = "cdsParser")
@Named("CDParser")
//@Named
@SessionScoped
public class CDParser implements Serializable{

    /**
     * 
     */
    private static final long serialVersionUID = 3890828719623315368L;
    @Named
    private List<CDXmlDescriptor> cdsList;

I cannot figure out the proper way to replace @ManagedProperty(value = "#{cdsParser.cdsList}") using CDI?


回答1:


Since your cdsList is no bean class you need a producer field or a producer method to make it injectable.

Example for producer field:

import javax.enterprise.inject.Produces;
...
@Named 
@Produces 
private List<CDXmlDescriptor> cdsList;

Example for producer method:

import javax.enterprise.inject.Produces;

private List <CDXmlDescriptor> cdsList;
...
@Named("cdsList") 
@Produces 
public List<CDXmlDescriptor> getCdsList {
  return cdsList;
};

This works if there is no other producer field or producer method that returns the same bean type. Otherwise you need to introduce a special qualifier for your producer field to resolve ambiguity:

import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.inject.Qualifier;


@Qualifier
@Retention(RUNTIME)
@Target({METHOD, FIELD, PARAMETER, TYPE})
public @interface CdsList {
}

with

@Named @Produces @CdsList
private List<CDXmlDescriptor> cdsList;


来源:https://stackoverflow.com/questions/9934458/cdi-replacement-for-managedproperty

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