Spring注入引起空指针异常的注释 [英] Spring Inject annotations causing nullpointer exception

查看:130
本文介绍了Spring注入引起空指针异常的注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这篇文章是 applicationContext.xml中bean的声明的连续性



我有一个使用Spring 3和Hibernate 4的JSF2的小应用程序,当我运行我正在运行的应用程序时。

  java.lang.NullPointerException在
net.test.managed.bean.EmployeesManagedBean.getEmpList(EmployeesManagedBean.java: 53)

我做错了什么来获取空指针异常?任何帮助都是非常可观的。

ManagedBean:

  @ManagedBean(名称=empMB)
@Named
@Scope(request)
public class EmployeesManagedBean实现可序列化{

public List< Employees> getEmpList(){
try {
empList = new ArrayList< Employees>();
empList.addAll(getEmployeesService()。getEmployees());
} catch(Exception e){
e.printStackTrace();
}
返回empList;


我注入了注解:

  @Inject 
EmployeesService employeesService;

在EmployeesService中,我有如下注释:

  @Named 
public class EmployeesService实现IEmployeesService {

@Inject
EmployeesDAO employeesDAO;

@Override
公共列表<雇员> getEmployees(){
return getEmployeesDAO()。getEmployees();
}

在EmployeesDAO中,我有如下注释:

  @Named 
public class EmployeesDAO implements IEmployeesDAO {


@Override
public List< Employees> getEmployees(){
List query = this.getSessionFactory()。getCurrentSession()。getNamedQuery(getEmp)。list();
返回查询;



$ b实体类:

$ b pre> @Entity
@ javax.persistence.NamedNativeQuery(name =getEmp,query ={?= call getemployees},resultClass = Employees.class,hints = { @ javax.persistence.QueryHint(name =org.hibernate.callable,value =true)})
@Table(name =EMPLOYEES)
public class Employees {

最后在applicationContext.xml中我有

 < context:component-scan base-package =net.test/> 

更新1:



@Component(empMB)或@Named(empMB)我得到以下例外:

  'empMB':注入自动装配的
依赖项失败;
嵌套异常是org.springframework.beans.factory.BeanCreationException:
无法自动装载字段:net.test.employees.service.EmployeesService
net.test.managed.bean.EmployeesManagedBean.employeesService ;
嵌套异常是org.springframework.beans.factory。
NoSuchBeanDefinitionException:没有为
依赖关系找到类型为
[net.test.employees.service.EmployeesService]的匹配bean:预计至少有1个符合自动布线的bean
此候选人依赖。依赖注释:{@ javax.inject.Inject()}

更新2



applicationContext.xml:

 < beans xmlns =http://www.springframework .org / schema / beans
xmlns:xsi =http://www.w3.org/2001/XMLSchema-instancexmlns:tx =http://www.springframework.org/schema/tx
xmlns:context =http://www.springframework.org/schema/context
xsi:schemaLocation =http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework。 org / schema / tx / spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-上下文3.0.xsd>

< context:component-scan base-package =net.test/>
<! - 数据源声明 - >
< bean id =DataSourceclass =com.mchange.v2.c3p0.ComboPooledDataSource
destroy-method =close>
< property name =driverClassvalue =oracle.jdbc/>
< property name =jdbcUrlvalue =jdbc:oracle:thin:@server:1521:DEV/>
< property name =uservalue =scott/>
< property name =passwordvalue =tiger/>
< property name =maxPoolSizevalue =10/>
< property name =maxStatementsvalue =0/>
< property name =minPoolSizevalue =5/>
< / bean>
<! - 会话工厂声明 - >
< bean id =SessionFactory
class =org.springframework.orm.hibernate4.LocalSessionFactoryBean>
< property name =dataSourceref =DataSource/>
< property name =hibernateProperties>
<道具>
< prop key =hibernate.dialect> org.hibernate.dialect.Oracle10gDialect< / prop>
< prop key =hibernate.show_sql> true< / prop>
< /道具>
< / property>
< / bean>
<! - 启用基于注释的事务行为配置 - >
< tx:annotation-driven transaction-manager =txManager/>
<! - 事务管理器已定义 - >
< bean id =txManager
class =org.springframework.orm.hibernate4.HibernateTransactionManager>
< property name =sessionFactoryref =SessionFactory/>
< / bean>
< / beans>


解决方案

我设法解决了获取空指针的问题例外,礼貌
Marten Deinum



我在做的错误是没有DAO类的 @Inject ,I已修改我的DAO类为

  @Named 
public class EmployeesDAO implements IEmployeesDAO {

@Inject
private SessionFactory sessionFactory;

@Override
公共列表<雇员> getEmployees(){

List query = sessionFactory.getCurrentSession()。getNamedQuery(getEmp)。list();

返回查询;






在ManagedBean中, Daniel使用 @Named 而不是 @ManagedBean 。修改后的ManagedBean

$ $ p $ code $ @ $(b


$ b $ public $ EmployeesManagedBean实现Serializable {

@Inject
IEmployeesService employeesService;

当然,在 applicationContext.xml 中添加以下内容来扫描实体类

 < property name =annotatedClasses> 
< list>
< value> net.test.model.Employees< / value>
< / list>
< / property>


This post is continuity of Declaration of beans in applicationContext.xml

I have a small application using Spring 3 and Hibernate 4 with JSF2, When I am running the application I am getting.

java.lang.NullPointerException at
net.test.managed.bean.EmployeesManagedBean.getEmpList(EmployeesManagedBean.java:53)

What am I doing wrongly to get nullpointer exception? Any help is highly appreciable.

ManagedBean:

@ManagedBean(name="empMB")
@Named
@Scope("request")
public class EmployeesManagedBean implements Serializable {

    public List<Employees> getEmpList() {
        try {
            empList = new ArrayList<Employees>();
            empList.addAll(getEmployeesService().getEmployees());
        } catch (Exception e) {
            e.printStackTrace();            
        }
        return empList;
    }
}

and I have Inject annotation:

@Inject
EmployeesService employeesService;

In EmployeesService I have annotations like:

@Named
public class EmployeesService implements IEmployeesService {

@Inject
EmployeesDAO employeesDAO;

@Override
public List<Employees> getEmployees() {
    return getEmployeesDAO().getEmployees();
}

In EmployeesDAO I have annotations like:

@Named
public class EmployeesDAO implements IEmployeesDAO {


@Override
public List<Employees> getEmployees() {
    List query = this.getSessionFactory().getCurrentSession().getNamedQuery("getEmp").list();               
    return query;
}

Entity class:

@Entity
@javax.persistence.NamedNativeQuery(name = "getEmp", query = "{ ? = call getemployees }", resultClass = Employees.class, hints = { @javax.persistence.QueryHint(name = "org.hibernate.callable", value = "true") })
@Table(name = "EMPLOYEES")
public class Employees {

and finally in applicationContext.xml I have

<context:component-scan base-package="net.test" />

Update 1:

When I use @Component("empMB") or @Named("empMB") I am getting the following exceptions

Error creating bean with name 'empMB': Injection of autowired 
dependencies failed;
nested exception is org.springframework.beans.factory.BeanCreationException: 
Could not autowire field: net.test.employees.service.EmployeesService
net.test.managed.bean.EmployeesManagedBean.employeesService; 
nested exception is org.springframework.beans.factory.
NoSuchBeanDefinitionException: No matching bean of type
[net.test.employees.service.EmployeesService] found for 
dependency: expected at least 1 bean which qualifies as autowire 
candidate for this dependency. Dependency annotations: {@javax.inject.Inject()}

Update 2

applicationContext.xml:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">  

    <context:component-scan base-package="net.test" />
    <!-- Data Source Declaration -->
<bean id="DataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
        destroy-method="close">
        <property name="driverClass" value="oracle.jdbc" />
        <property name="jdbcUrl" value="jdbc:oracle:thin:@server:1521:DEV" />
        <property name="user" value="scott" />
        <property name="password" value="tiger" />
        <property name="maxPoolSize" value="10" />
        <property name="maxStatements" value="0" />
        <property name="minPoolSize" value="5" />
    </bean> 
    <!-- Session Factory Declaration -->
    <bean id="SessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="DataSource" />     
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>
    <!-- Enable the configuration of transactional behavior based on annotations -->
    <tx:annotation-driven transaction-manager="txManager" />
    <!-- Transaction Manager is defined -->
    <bean id="txManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="SessionFactory" />
    </bean>
</beans>

解决方案

I have managed to resolve the issue of getting null pointer exception, courtesy to Marten Deinum

The mistake what I was doing was there were no @Inject for DAO class, I have modified my DAO class as

@Named
public class EmployeesDAO implements IEmployeesDAO {

    @Inject
    private SessionFactory sessionFactory;

    @Override
    public List<Employees> getEmployees() {

             List query = sessionFactory.getCurrentSession().getNamedQuery("getEmp").list();

        return query;
    }
}

and in ManagedBean I have made the changes as mentioned by Daniel to use @Named instead of @ManagedBean. Modified ManagedBean

@Named("empMB")
@Scope("request")
public class EmployeesManagedBean implements Serializable {

    @Inject
    IEmployeesService employeesService;

And of course added the following in applicationContext.xml to scan Entity class

<property name="annotatedClasses">  
          <list>
           <value>net.test.model.Employees</value>
           </list>  
           </property> 

这篇关于Spring注入引起空指针异常的注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆