This question already has an answer here:
- Why is my Spring @Autowired field null? 14 answers
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" />
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;
}
}
Here's my Main Class
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)
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: i am new on learning spring
You will want to use
@PersistenceContext
for injecting theEntityManager
.See
PersistenceContext EntityManager injection NullPointerException
which is pretty much the same question.
Since you are instantiating
TeacherDaoImpl
yourself (with thenew
keyword) within main, Spring is not injecting theEntityManager
and hence the NPE.Annotate the field
TeacherDaoImpl.entityManager
with@PersistenceContext
and annotate theTeacherDaoImpl
class with@Component
to have Spring instantiate it for you. Then in your main, get a hold of that bean:Also these two directives seem to be unnecessary:
The former is implied when you are using
<context:component-scan />
. The latter is only useful if you are using@Configurable
in your code.