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

Ern*_*ano 5 spring entitymanager

这是我的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" />
Run Code Online (Sandbox Code Playgroud)

这是我的Dao实现

public class TeacherDaoImpl implements TeacherDao {

@Autowired
private EntityManager entityManager;

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

}
Run Code Online (Sandbox Code Playgroud)

}

这是我的主班

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"));

}
Run Code Online (Sandbox Code Playgroud)

}

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

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)
Run Code Online (Sandbox Code Playgroud)

香港专业教育学院一直在解决这个问题的两天,但我仍然找不到任何资源可以解决这个问题。如果您给我您的意见,答案或任何可能帮助我解决此问题的想法,我将不胜感激,

ps:我是新来的学习春季的人

Juk*_*kka 5

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

对字段进行注释TeacherDaoImpl.entityManager@PersistenceContextTeacherDaoImpl类进行注释@Component,让 Spring 为您实例化它。然后在你的 main 中,获取那个 bean:

TeacherDao dao = applicationContext.getBean(TeacherDao.class);
// ...
Run Code Online (Sandbox Code Playgroud)

这两个指令似乎也是不必要的:

<context:annotation-config />
<context:spring-configured />
Run Code Online (Sandbox Code Playgroud)

当您使用 时,前者是隐含的<context:component-scan />。后者仅在您@Configurable在代码中使用时才有用。


归档时间:

查看次数:

18195 次

最近记录:

12 年,3 月 前