您好,我正在尝试使用 h:datatable 标记在 JSF 中加载页面的学生列表
<h:dataTable value="#{studentBean2.studentList}" var="student">
......
.....
</h:datatable>
现在我的ManagedBean如下
public class StudentBeanTwo {
public StudentBeanTwo() {
init();
}
@Resource(name="jdbc/rahul_sample_pool",type=DataSource.class)
private DataSource dataSource;
private void init(){
.......
.......
if(this.getStudentList() == null){
loadStudents();
}
}
private void loadStudents() throws Exception{
Connection con = null;
.....
.....
try{
if(this.dataSource == null){
System.out.println(" DataSource() is null ");
}
con = this.dataSource.getConnection();
........
}
}
现在我的问题是为什么我的数据源为空,
我通过将 @Resource 注释到另一个 servlet 中的变量来检查我是 能够创建连接,
那么上面的managed-bean有什么问题,
为什么数据源为空? 容器无法注入(inject)资源,为什么?
请帮帮我
最佳答案
除了 Björns 的评论:注入(inject)在 构造之后完成,您从构造函数调用 init 方法。
您可以使用@PostConstruct
注释您的init()
方法。然后在构建之后调用,而不是在构建过程中调用。
import javax.annotation.PostConstruct;
...
@PostConstruct
private void init(){
...
if(this.getStudentList() == null){
loadStudents();
}
}
然后每次构造 bean 时都会调用 init 方法(取决于 bean 的范围)。
关于java - 无法在托管 Bean 中注入(inject)数据源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8090822/