当前位置: 首页 > 知识库问答 >
问题:

@Inject Dao上的java.lang.NullPointerException

缪茂勋
2023-03-14

我试图将DAO注入@Service组件,但我得到了以下错误:

线程mainjava.lang.NullPointerExceptionit.cle.project.service.impl.TestEntityServiceImpl.getListTestEntity(TestEntityServiceImpl.java:24)的异常。

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

上下文.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);
}

摘要HbnDao 摘要类:

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 class 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);
}

}

有什么想法吗?谢了。

共有2个答案

微生俊材
2023-03-14

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

 TestEntityServiceImpl testEntityServiceImpl = new TestEntityServiceImpl();

您创建了一个非托管bean。Spring对此无能为力。将< code > TestEntityServiceImpl 放入spring上下文中。

班展
2023-03-14

你的测试服务Impl应该是Spring管理的bean,应该从Spring应用程序上下文中获取(通过注入或通过显式询问上下文)。由于组件扫描正在工作,您的测试服务已经使用Spring自己提供的名称进行管理(com...测试服务简单变为测试服务简单)。你可以给它你的名字,就像

@Service("myTestServiceImpl")

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

 类似资料:
  • Animal.java 我为它创建了以下自定义断言: AnimalAssert.java 编辑:基于第一个答案(cglib需要一个),我用一个no arg构造函数更新了动物类,但是抛出了相同的异常

  • 我的应用程序一直在许多Android平台上报告这个问题(4.1、4.0.4、2.3.6.…)。但我无法在我的手机上复制这个问题。我已经在Google上搜索了这个问题,但堆栈跟踪似乎与我的不一样。

  • 我有一台带有Intel CPU的Windows机器(在引导菜单上启用VMX)。我使用VirtualBox在上面运行Ubuntu Guest。我在上面运行qemu,以运行另一个Guest OS,使用kvm(选项)。 我在尝试插入kvm-intel模块时收到以下错误: 我已经检查了来宾操作系统中的vpx标志,但我也没有看到 有没有办法在来宾Ubuntu操作系统中启用kvm支持,以便我可以在Ubuntu

  • 我试图发送一个GET请求,传递一个身份验证令牌头以获取一些JSON数据,但是我得到了所有的java.lang.NullPointerExceptions。我已经尝试使用JSONObjectRequest、JSONArrayRequest甚至StringRequest。 下面是代码(JSONObjectRequest和JSONArrayRequest对测试进行了注释): 我可能找到了有用的东西。我移

  • 我试图从java程序中使用Spark SQL,其中pom.xml中的依赖关系指向Spark版本1.6.0。下面是程序 但是,我在线程“main”java.lang.nosuchmethoderror:org.apache.spark.sql.sqlcontext.sql(ljava/lang/string;)lorg/apache/spark/sql/dataframe中出现异常;我正在创建一个平

  • 主机系统为ARCHLinux。我想开发需要运行Windows docker容器的.NET4.6.1应用程序。所以我在VirtualBox下运行Win10。然后我在Win10中安装Docker,以运行Windows Docker容器。Linux->VirtualBox->Win10->Docker->Windows Docker容器->要运行的应用程序。 或者更具体地说,VirtualBox是否支持