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;

}

}

これが私のメインクラスです

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)

この問題を 2 日で解決しましたが、この問題を解決できるリソースはまだ見つかりません。あなたの意見、回答、またはこれを解決するのに役立つアイデアを教えていただければ幸いです。

ps:私は春を学ぶのが初めてです

4

2 に答える 2

4

main 内でTeacherDaoImpl(キーワードを使用して) 自分自身をインスタンス化しているため、Spring は を注入していないため、NPE を注入していません。newEntityManager

フィールドTeacherDaoImpl.entityManager@PersistenceContextでアノテーションを付け、TeacherDaoImplクラスに でアノテーションを付けて、 @ComponentSpring にインスタンス化させます。次に、メインで、その Bean を取得します。

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

また、次の 2 つのディレクティブは不要のようです。

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

を使用しているときは、前者が暗示されます<context:component-scan />。後者は、コードで使用している場合にのみ役立ち@Configurableます。

于 2013-10-01T06:05:36.277 に答える
3

@PersistenceContextを注入するために使用する必要がありEntityManagerます。

見る

PersistenceContext EntityManager インジェクション NullPointerException

これはほとんど同じ質問です。

于 2013-10-01T05:22:20.203 に答える