代码之家  ›  专栏  ›  技术社区  ›  Ernest Hilvano

使用Spring注入EntityManager(Null指针异常)[重复]

  •  8
  • Ernest Hilvano  · 技术社区  · 11 年前

    这是我的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 Implementation

    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)
    

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

    ps:我是春季学习新手

    2 回复  |  直到 11 年前
        1
  •  4
  •   Jukka    11 年前

    由于您正在实例化 TeacherDaoImpl 你自己(和 new 关键字),Spring没有注入 EntityManager 从而产生NPE。

    为字段添加注释 TeacherDaoImpl.entityManager 具有 @PersistenceContext 并对 教师指导实施 与一起上课 @Component 让Spring为您实例化它。然后,在你的主菜中,抓住那颗豆子:

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

    此外,这两项指令似乎没有必要:

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

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

        2
  •  3
  •   Community CDub    7 年前

    您将想要使用 @PersistenceContext 用于注射 EntityManager .

    看见

    PersistenceContext EntityManager injection NullPointerException

    这几乎是同一个问题。