【问题标题】:java.lang.NullPointerException on @Inject Dao@Inject Dao 上的 java.lang.NullPointerException
【发布时间】:2014-04-07 11:03:54
【问题描述】:

我正在尝试将 DAO 注入 @Service 组件,但出现此错误:

线程“main”中的异常 java.lang.NullPointerException at it.cle.project.service.impl.TestEntityServiceImpl.getListTestEntity(TestEntityServiceImpl.java:24)。

尽管有 @Autowired 注释,但调用为空的 DAO 失败 在我的代码下面:

context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans  xmlns="http://www.springframework.org/schema/beans"
    xmlns:c="http://www.springframework.org/schema/c"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/jee
    http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    http://www.springframework.org/schema/util
    http://www.springframework.org/schema/util/spring-util-4.0.xsd">

<!-- INIZIO IMPOSTAZIONI LEGATE ALLE ANNOTATIONS -->
<tx:annotation-driven/>
<context:property-placeholder location="classpath:hibernate.properties"/>
<context:component-scan base-package="it.cle.project.service.impl" />
<context:component-scan base-package="it.cle.project.dao.hbn" />
<context:component-scan base-package="it.cle.project.dao.hibernate" />
<!-- FINE IMPOSTAZIONI LEGATE ALLE ANNOTATIONS -->


<!-- INIZIO IMPOSTAZIONI LEGATE AD ALTRI FILE DI CONFIGURAZIONE -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location" value="classpath:hibernate.properties"/>
</bean>
<!-- FINE IMPOSTAZIONI LEGATE AD ALTRI FILE DI CONFIGURAZIONE -->


<!-- INIZIO IMPOSTAZIONI LEGATE ALLA CONNESSIONE -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager" p:sessionFactory-ref="sessionFactory" />

<util:properties id="hibernateProperties">
    <prop key="hibernate.dialect">${hibernate.dialect}</prop>
    <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
    <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl_auto}</prop>
</util:properties>

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"
    p:driverClassName="${jdbc.driverClassName}"
    p:url="${jdbc.url}"
    p:username="${jdbc.username}"
    p:password="${jdbc.password}" />

<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean "
    p:dataSource-ref="dataSource" p:packagesToScan="it.cle.project.model" 
    p:hibernateProperties-ref="hibernateProperties" /> 
<!-- FINE IMPOSTAZIONI LEGATE ALLA CONNESSIONE -->

App.java

package it.cle.project;
import it.cle.project.model.TestEntity;
import it.cle.project.service.impl.TestEntityServiceImpl;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App 
{
public static void main( String[] args )
{
    ApplicationContext context =  new ClassPathXmlApplicationContext("context.xml");


    System.out.println( "Hello World!" );
    TestEntity testEntity = new TestEntity();
    testEntity.setCampoUno("Campo Uno");
    testEntity.setCampoDue("Campo Due");
    testEntity.setEmail("email@test.it");



    TestEntityServiceImpl testEntityServiceImpl = new TestEntityServiceImpl();

    List<TestEntity> testEntitys = testEntityServiceImpl.getListTestEntity();


     }
}

DAO 接口

package it.cle.project.dao;
import java.io.Serializable;
import java.util.List;
public interface Dao<T extends Object> {
void create(T t);

T get(Serializable id);

T load(Serializable id);

List<T> getAll();

void update(T t);

void delete(T t);

void deleteById(Serializable id);

void deleteAll();

long count();

boolean exists(Serializable id);
}

TestEntityDAO 接口

package it.cle.project.dao;
import it.cle.project.model.TestEntity;
import java.util.List;
public interface TestEntityDao extends Dao<TestEntity> {
List<TestEntity> findByEmail(String email);
}

AbstractHbnDao 抽象类:

package it.cle.project.dao.hibernate;
import it.cle.project.dao.Dao;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.util.Date;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ReflectionUtils;
@Service
public abstract class AbstractHbnDao<T extends Object> implements Dao<T> {

@Autowired
private SessionFactory sessionFactory;

private Class<T> domainClass;

protected Session getSession() {
    return sessionFactory.getCurrentSession();
}

@SuppressWarnings("unchecked")
private Class<T> getDomainClass() {
    if (domainClass == null) {
    ParameterizedType thisType =
    (ParameterizedType) getClass().getGenericSuperclass();
    this.domainClass =
    (Class<T>) thisType.getActualTypeArguments()[0];
    }
    return domainClass;
}

private String getDomainClassName() {
    return getDomainClass().getName();
}

public void create(T t) {
    Method method = ReflectionUtils.findMethod(
    getDomainClass(), "setDataCreazione",
    new Class[] { Date.class });
    if (method != null) {
        try {
        method.invoke(t, new Date());
        } catch (Exception e) { /* Ignore */ }
    }
    getSession().save(t);
}

@SuppressWarnings("unchecked")
public T get(Serializable id) {
    return (T) getSession().get(getDomainClass(), id);
}

@SuppressWarnings("unchecked")
public T load(Serializable id) {
    return (T) getSession().load(getDomainClass(), id);
}

@SuppressWarnings("unchecked")
public List<T> getAll() {
    return getSession()
    .createQuery("from " + getDomainClassName())
    .list();
}

public void update(T t) { getSession().update(t); }

public void delete(T t) { getSession().delete(t); }

public void deleteById(Serializable id) { delete(load(id)); }

public void deleteAll() {   
    getSession()
    .createQuery("delete " + getDomainClassName())
    .executeUpdate();
}

public long count() {
    return (Long) getSession()
    .createQuery("select count(*) from " + getDomainClassName())
    .uniqueResult();
}

public boolean exists(Serializable id) { return (get(id) != null); }
}

HbnTestEntityDao 类 DAO

package it.cle.project.dao.hbn;
import it.cle.project.dao.TestEntityDao;
import it.cle.project.dao.hibernate.AbstractHbnDao;
import it.cle.project.model.TestEntity;
import java.util.List;
import org.springframework.stereotype.Repository;
@Repository
public class HbnTestEntityDao extends AbstractHbnDao<TestEntity> implements TestEntityDao {

@SuppressWarnings("unchecked")
public List<TestEntity> findByEmail(String email) {
    return getSession()
    .getNamedQuery("findContactsByEmail")
    .setString("email", "%" + email + "%")
    .list();
}
}

TestEntityService 接口服务

package it.cle.project.service;
import it.cle.project.model.TestEntity;
import java.util.List;
public interface TestEntityService {

void createTestEntity(TestEntity testEntity);

List<TestEntity> getListTestEntity();

List<TestEntity> getTestEntityByEmail(String email);

TestEntity getTestEntity(Integer id);

void updateTestEntity(TestEntity testEntity);

void deleteTestEntity(Integer id);
}

TestEntityServiceImpl

package it.cle.project.service.impl;
import it.cle.project.dao.TestEntityDao;
import it.cle.project.model.TestEntity;
import it.cle.project.service.TestEntityService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
public class TestEntityServiceImpl implements TestEntityService {

@Autowired
private TestEntityDao testEntityDao;

public void createTestEntity(TestEntity testEntity) {
    testEntityDao.create(testEntity);
}

public List<TestEntity> getListTestEntity() {
    return testEntityDao.getAll();
}

public List<TestEntity> getTestEntityByEmail(String email) {
    return testEntityDao.findByEmail(email);
}

public TestEntity getTestEntity(Integer id) {
    return testEntityDao.get(id);
}

public void updateTestEntity(TestEntity testEntity) {
    testEntityDao.update(testEntity);
}

public void deleteTestEntity(Integer id) {
    testEntityDao.deleteById(id);
}

}

有什么想法吗? 谢谢。

【问题讨论】:

    标签: spring hibernate dao autowired inject


    【解决方案1】:

    这是一些文字墙。我停在:

     TestEntityServiceImpl testEntityServiceImpl = new TestEntityServiceImpl();
    

    您创建了一个非托管 bean。 Spring 无法控制这一点。将 TestEntityServiceImpl 放入您的 spring 上下文中。

    【讨论】:

    • 我将 TestEntityServiceImpl 配置为 @Service。错了吗?
    • 没错。用new在spring容器外创建实例是错误的。
    【解决方案2】:

    您的 TestServiceImpl 应该是 spring 管理的 bean,并且应该从 Spring 应用程序上下文中获取(通过注入或通过显式询问上下文)。由于组件扫描工作,您的TestServiceImpl 已经使用 Spring 自己提供的名称进行管理(com...TestServiceImpl 变为 testServiceImpl)。你可以给它你的名字,比如

    @Service("myTestServiceImpl")
    

    您可以从应用程序上下文中查询这个命名的 bean 并使用它,而不是自己创建 bean。

    【讨论】:

    • 我已将@Service 更改为@Service("testServiceImpl") 并调用TestEntityServiceImpl testEntityServiceImpl = (TestEntityServiceImpl) context.getBean ("testServiceImpl");给出此错误:线程“main”中的异常 java.lang.ClassCastException: com.sun.proxy.$Proxy29 不能在 it.cle.project.App.main 处转换为 it.cle.project.service.impl.TestEntityServiceImpl( App.java:32)
    • 默认情况下Spring使用JDK动态代理为目标类(在本例中为TestServiceImpl)生成代理,只要TestServiceImpl实现一个接口TestEntityService。因此,您会将查找转换为 TestEntityService 而不是 TestServiceImpl。顺便说一句,在接口方面工作总是很好的做法
    猜你喜欢
    • 2016-12-04
    • 2012-06-10
    • 1970-01-01
    • 2016-08-02
    • 1970-01-01
    • 2013-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多