作者lueichun (= =)
看板java
标题[问题] 使用CDI注入物件到属性
时间Sat Jan 2 23:04:45 2021
※状况概述:
我尝试用CDI,将DAO物件注入到位於某个Action的DAO属性里,不过都失败,看起来是
注入没有成功。
※程式码:
DAO:
@Named
@ApplicationScoped
public class TestDao {
......
}
Action:
@ManagedBean(name="testAction")
@SessionScoped
public class TestAction {
@Inject
TestDao testDao;
public List<Customer> query(){
customerList = testDao.query();//执行到这行出错
}
※错误讯息:
com.sun.faces.lifecycle.InvokeApplicationPhase execute
警告: #{testAction.query()}: java.lang.NullPointerException
javax.faces.FacesException: #{testAction.query()}:
java.lang.NullPointerException
threw exception [java.lang.NullPointerException] with root cause
java.lang.NullPointerException
※补充说明:
看起来是注入没有成功才会跳NullPointerException,
DAO有用@Named跟@ApplicationScoped来注册物件跟指定存在的scope
action也有用@inject宣告要注入的属性
那请问要如何修改才能修正呢?
--------------------------------
结果我放弃CDI的写法,改用纯JSF的写法:
@ManagedBean(name="testDao")
@SessionScoped
//改写成这样
public class TestDao {
List<Customer> customerList;
public List<Customer> query(){
......
}
}
@ManagedBean(name="testAction")
@SessionScoped
public class TestAction {
List<Customer> customerList;
@ManagedProperty(value="#{testDao}")
//改写成这样
TestDao testDao;
public List<Customer> query(){
customerList = testDao.query();
}
//新增以下部分:
public TestDao getTestDao() {
return testDao;
}
public void setTestDao(TestDao testDao) {
this.testDao = testDao;
}
}
暂时改成JSF的写法就可以动,不过还是不懂为何用CDI就不行。
将Server由Tomcat改成wildfly後,原本CDI的语法即可运作,
看来是Tomcat不支援CDI的关系。
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 1.169.110.42 (台湾)
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/java/M.1609599887.A.06E.html
※ 编辑: lueichun (1.160.35.165 台湾), 01/03/2021 22:04:27