java - 无法在托管 Bean 中注入(inject)数据源

标签 java jsf dependency-injection jsf-2

您好,我正在尝试使用 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/

相关文章:

java - 附加代码点()和代码点()

java - 如何在 IBM Tivoli Identity Manager 中添加角色

java - 跨 weblogic 集群环境的序列化测试

eclipse - Eclipse 4 DI 的最佳实践

java - 有没有办法对 Azure 数据工厂中的数据进行分区以填充文件,直到达到最大行值?

java - JFace TableViewer 像 Excel 一样在单元格上绘制矩形

java - 如何关闭 Icefaces 日志记录?

jsf - 使用图像作为 p :selectOneRadio 的标签

java - 类字段同时具有@Autowired 注释和右手赋值

dependency-injection - Ninject:如何从工厂访问NamedScope的根对象