使用Spring注入EntityManager(空指针异常) [英] Injecting EntityManager using Spring ( Null Pointer Exception )
问题描述
这是我的ApplicationContext.xml的代码
Here's the code insidy my 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实现方案
and here's my 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"));
}
}
请帮助,我得到一个空指针异常
Please help, i am getting a null pointer exception
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天内解决了这个问题,但是我仍然找不到任何可以解决这个问题的资源。
ive been solving this problem in 2 days but still i cant find any resources that may solve this problem. i appreciate if you give me your opinion,answers or any idea that might help me solving this,
ps:我对学习春天感到陌生
ps: i am new on learning spring
推荐答案
由于您是自己实例化 TeacherDaoImpl
(使用 new $ c)中没有添加
EntityManager
以及NPE。
Since you are instantiating TeacherDaoImpl
yourself (with the new
keyword) within main, Spring is not injecting the EntityManager
and hence the NPE.
字段 TeacherDaoImpl.entityManager
与 @PersistenceContext
并注释 TeacherDaoImpl
带有 @Component
的类,让Spring为您实例化它。然后在您的主体中,获得该bean的所有权:
Annotate the field TeacherDaoImpl.entityManager
with @PersistenceContext
and annotate the TeacherDaoImpl
class with @Component
to have Spring instantiate it for you. Then in your main, get a hold of that bean:
TeacherDao dao = applicationContext.getBean(TeacherDao.class);
// ...
这两个指令似乎也是不必要的:
Also these two directives seem to be unnecessary:
<context:annotation-config />
<context:spring-configured />
在使用< context:component-scan时隐含前者/>
。仅当您在代码中使用 @Configurable
时,后者才有用。
The former is implied when you are using <context:component-scan />
. The latter is only useful if you are using @Configurable
in your code.
这篇关于使用Spring注入EntityManager(空指针异常)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!