使用Spring注入EntityManager(空指针异常)

8
这里是我的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" />

这是我的Dao实现

public class TeacherDaoImpl implements TeacherDao {

@Autowired
private EntityManager entityManager;

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

}

以下是我的主类:

class Main { }

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)

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

附注:我是初学Spring的新手。

2个回答

5

由于您在main方法中使用new关键字自行实例化了TeacherDaoImpl,因此Spring无法注入EntityManager,导致出现NPE。

请给TeacherDaoImpl.entityManager字段添加@PersistenceContext注解,并给TeacherDaoImpl类添加@Component注解,以便让Spring替您进行实例化。然后在您的main方法中获取该bean:

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

此外,这两个指令似乎是不必要的:

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

如果您使用<context:component-scan />,那么前者是默认的。而后者只在您的代码中使用@Configurable时才有用。


嗨,谢谢。看起来我快要解决这个问题了,但是出现了新的错误。 org.springframework.beans.factory.NoSuchBeanDefinitionException: 未定义名为“transactionManager”的bean。 - Ernest Hilvano
你知道在bean上作为transactionmanager添加的确切类是什么吗? - Ernest Hilvano
现在它可以工作了,我刚刚添加了<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory" /> </bean> - Ernest Hilvano
下一个问题是,我如何使用注解自动地使用TeacherDao,而不使用of = applicationContext.getBean(TeacherDao.class)? - Ernest Hilvano
如果您希望使用新的关键字并仍然注入依赖项,请在Spring中查找@Configurable和AspectJ。如有必要,请提出一个新的stackoverflow问题。但是请先花费一些时间/思考它。 - Jukka
无论如何,只是想说非常感谢。 :) 我很高兴它现在可以工作了,也许我不能在J2SE上进行自动注入,可能@ Autowired会在JEE上工作。 - Ernest Hilvano

3

嗨,我已经在TeacherDaoImpl中更改了EntityManager字段上面的Autowired注释,但仍然没有运气,请帮忙 :) - Ernest Hilvano

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接