我想使用注解@Inject 或@Produce 在ManagedBean 中注入一个CDI Bean。我使用的 CDI Bean 是:
@Named
@Startup
@ApplicationScoped
public class BaseBean {
private List<String> custs;
public List<String> getCusts() {
return custs;
}
public void setCusts(List<String> emps) {
this.custs = emps;
}
public BaseBean(){
}
@PostConstruct
void init() {
custs = new ArrayList<String>();
custs.add("Cust1");
custs.add("Cust3");
custs.add("Cust2");
custs.add("Cust4");
}
}
我要在其中注入 CDI Bean 的 ManagedBean 是:
@SessionScoped
@ManagedBean
public class Hello implements Serializable {
@Inject
private BaseBean dBean;
private static final long serialVersionUID = 1L;
private List<String> customers;
private List<String> customersSelect;
public Hello() {
}
@PostConstruct
void init() {
// dBean = new BaseBean();
customers = dBean.getCusts();
}
public List<String> getCustomers() {
return customers;
}
public List<String> getCustomersSelect() {
return customersSelect;
}
public void setCustomersSelect(List<String> customersSelect) {
this.customersSelect = customersSelect;
}
}
然而,在 init 函数中,它会抛出 NullPointerException。如果我使用注解@Produces 而不是@Inject,结果是一样的:NullPointerException。CDI Bean 有什么问题(不正确的注释)吗?我是否尝试以错误的方式注入它?我的代码缺少什么吗?我怎样才能让它工作?这是JSF代码:
<h:form id ="f">
<h:selectManyCheckbox layout="pageDirection" border="1" value="#{hello.customersSelect}">
<f:selectItems value="#{hello.customers}"></f:selectItems>
</h:selectManyCheckbox><br />
<h:commandButton action="response.xhtml" value="Click me" />
</h:form>
PS:如果我使用无状态 Bean 作为 BaseBean 并使用注解 @EJB 注入它,则它可以正常工作。
更新:我已经在注释@SessionScoped
(javax.enterprise.context.SessionScoped
)和课堂@Named
上尝试过。Hello
虽然我没有收到 a NullPointerException
,但h:selectManyCheckbox
它是空的。此外,令我震惊的是,当我在文件夹beans.xml
下添加文件时META-INF
,我收到一个StartException
,尽管该文件应该存在。我认为我的应用程序缺少能够进行依赖注入的正确配置。什么可能需要额外的配置?
更新 2:当我在 WEB-INF 文件夹中添加 beans.xml 文件时出现此错误。beans.xml 文件是空的,它只包含以下行:
<?xml version="1.0" encoding="UTF-8"?>
错误是:
Services which failed to start: service jboss.deployment.unit."JSF1.war".PARSE: org.jboss.msc.service.StartException in service jboss.deployment.unit."JSF1.war".PARSE: Failed to process phase PARSE of deployment "JSF1.war"
12:51:11,482 ERROR [org.jboss.as.server.deployment.scanner] (DeploymentScanner-threads - 1) {"JBAS014653: Composite operation failed and was rolled back. Steps that failed:" => {"Operation step-2" => {"JBAS014671: Failed services" => {"jboss.deployment.unit.\"JSF1.war\".PARSE" => "org.jboss.msc.service.StartException in service jboss.deployment.unit.\"JSF1.war\".PARSE: Failed to process phase PARSE of deployment \"JSF1.war\""}}}}