繁体   English   中英

无法在Managed Bean中注入Datasource

[英]Unable to inject Datasource in Managed Bean

您好我正在尝试使用h:datatable标记加载JSF中的学生onload of Page

<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();
       ........
    }
}

现在我的问题是为什么我的数据源是null,

我通过将@Resource注释到另一个servlet中的变量来检查我是否能够创建连接,

那么上面的托管bean中的问题是什么,

为什么datasource为null? 容器无法注入资源,为什么?

请帮帮我

除了Björns之外注释:注入是构造之后完成的,你可以从构造函数中调用init方法。

您可以使用@PostConstruct注释init()方法。 然后它将在施工后调用,而不是在施工期间调用。

import javax.annotation.PostConstruct;
...
    @PostConstruct
    private void init(){
        ...
        if(this.getStudentList() == null){
           loadStudents();              
        }   
    }

然后每次构造bean时都会调用init方法(取决于bean的作用域)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM