【问题标题】:Injecting EntityManager using Spring ( Null Pointer Exception ) [duplicate]使用 Spring 注入 EntityManager(空指针异常)[重复]
【发布时间】:2013-10-07 03:49:13
【问题描述】:

这是我的 ApplicationContext.xml 中的代码

    <context:spring-configured />
<context:annotation-config />
<context:component-scan base-package="com.apsas.jpa" />
<tx:annotation-driven />

<bean id="entityManagerFactory"
    class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
    <property name="persistenceUnitName" value="testjpa" />
</bean>

<bean id="entityManager"
    class="org.springframework.orm.jpa.support.SharedEntityManagerBean">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
    class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

这是我的道实现

public class TeacherDaoImpl implements TeacherDao {

@Autowired
private EntityManager entityManager;

@Transactional
public Teacher addTeacher(Teacher teacher) {
    entityManager.persist(teacher);
    return teacher;

}

}

这是我的主要课程

public class TestApp {

public static void main(String[] args) {

    ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
            "config/ApplicationContext.xml");       

    TeacherDao teacherDao = new TeacherDaoImpl();       
    Teacher teacher1 =  teacherDao.addTeacher(new Teacher("First Teacher"));

}

}

请帮忙,我得到一个空指针异常

Exception in thread "main" java.lang.NullPointerException
at com.apsas.jpa.dao.impl.TeacherDaoImpl.addTeacher(TeacherDaoImpl.java:22)
at com.apsas.jpa.main.TestApp.main(TestApp.java:26)

我已经在 2 天内解决了这个问题,但我仍然找不到任何可以解决这个问题的资源。如果您给我您的意见、答案或任何可能帮助我解决此问题的想法,我将不胜感激,

ps:我是学习spring的新手

【问题讨论】:

    标签: spring entitymanager


    【解决方案1】:

    由于您自己在 main 中实例化 TeacherDaoImpl(使用 new 关键字),因此 Spring 不会注入 EntityManager 并因此注入 NPE。

    @PersistenceContext 注释字段TeacherDaoImpl.entityManager 并用@Component 注释TeacherDaoImpl 类,让Spring 为您实例化它。然后在你的 main 中,抓住那个 bean:

    TeacherDao dao = applicationContext.getBean(TeacherDao.class);
    // ...
    

    这两个指令似乎也没有必要:

    <context:annotation-config />
    <context:spring-configured />
    

    当您使用&lt;context:component-scan /&gt; 时,会隐含前者。后者仅在您在代码中使用 @Configurable 时才有用。

    【讨论】:

    • 嗨,谢谢,似乎我即将解决这个问题,出现了新错误 org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'transactionManager' is defined
    • 您知道将作为事务管理器添加到 bean 上的确切类是什么吗?
    • 它现在工作了,我刚刚添加了
    • 下一个问题,不使用of = applicationContext.getBean(TeacherDao.class);
    • 如果您希望使用 new 关键字并且仍然注入依赖项,请在谷歌上搜索 @Configurable 和带有 Spring 的 AspectJ。如有必要,提出一个新的 stackoverflow 问题。但请先花一些时间/思考一下。
    【解决方案2】:

    您将需要使用@PersistenceContext 来注入EntityManager

    PersistenceContext EntityManager injection NullPointerException

    这几乎是同一个问题。

    【讨论】:

    • 嗨,我更改了 TeacherDaoImpl 中 EntityManager 字段上方的 Autowired 注释,但仍然没有成功,请帮忙:)
    猜你喜欢
    • 2013-06-08
    • 1970-01-01
    • 2023-04-10
    • 2019-07-08
    • 2014-02-04
    • 2017-10-22
    相关资源
    最近更新 更多