私はJava EE 7でプロジェクトに取り掛かりました。[email protected]
beanを別のものに注入する必要があります。どちらの豆は、類似した構造を持っている:@Stateless beanに注入するときに@Injectが失敗する
@Stateless
public class OperationRepository extends GenericRepository<Operation> {
@PersistenceContext
private EntityManager entityManager;
public OperationRepository() {
}
/*Implementation of abstract methods, getters/setters, etc*/
}
@Stateless
public class MenuRepository extends GenericRepository<Menu> {
@PersistenceContext
private EntityManager entityManager;
@Inject
private OperationRepository operationRepository;
public MenuRepository() {
}
/*idem OperationRepository*/
public List<Menu> getMenuFromOperation(...) {
// Do something where I need operationRepository
}
}
GenericRepository<E>
は、いくつかの一般的な方法や他の抽象メソッドを持つだけの抽象クラスであるここでは関係ありません。
問題は、getMenuFromOperation()
メソッドでNullPointerExceptionが発生することです。コードのデバッグ私は、注入されたoperationRepository
がメソッドで要求されたときにnullであることを認識しました。
なぜ注入ポイントに失敗しますか?私はここで何が欠けているのですか?ほんの少しのテストを行うために
、私はあなたの答えを事前に
おかげで(nullである)MenuRepository
コンストラクタでデフォルトOperationRepository
をインスタンス化することによって、手動で注入され、その場合にはOperationRepository.entityManager
が注入されていません。
編集#1
John Amentが要求したとして、ここではそれが行く:
- すべての私のコードは、単一の
jar
のファイルです。これは、Glassfish Server 4.1にWebモジュール(war
パッケージ)とともにデプロイされるMavenモジュールです。私はまだ開発していますので - は、プロジェクトをデプロイする準備ができていないので、まだ、まだ存在しません
beans.xml
MenuRepository
が@Test
クラスから利用され(私はまだ統合テストを実行しませんでした)MenuRepository
。public class MenuOperationRepositoryUTest extends BaseTestRepository { private MenuRepository menuRepository; private OperationRepository operationRepository; @Before public void initTestCase() { initTestDB(); menuRepository = new MenuRepository(); menuRepository.setEntityManager(em); operationRepository = new OperationRepository(); operationRepository.setEntityManager(em); } @After public void finalizeTestCase() { closeEntityManager(); } /*Some successful tests*/ @Test public void showMenuFromOperation() { // Insert some dummy data into the test DB (HSQL) // This method needs the injected OperationRepository in MenuRepository List<Menu> menu = menuRepository.getMenuFromOperation(...); // Assertions } }
、次のようにBaseTestRepositoryは次のとおりです:次のよう
テストクラスのためのコードがある
@Ignore
public class BaseTestRepository {
private EntityManagerFactory emf;
protected EntityManager em;
// This is a helper class that contains all the boilerplate to begin transaction
// and commit, it's used to insert data in the test DB
protected DBCommandExecutor dbCommandExecutor;
protected void initTestDB() {
// sigeaPU is the name declared in persistence.xml
emf = Persistence.createEntityManagerFactory("sigeaPU");
em = emf.createEntityManager();
dbCommandExecutor = new DBCommandExecutor(em);
}
protected void closeEntityManager() {
em.close();
emf.close();
}
}
は、私はそれは私がこれまでに得たすべてだと思います。
インターフェイスで「@ Inject」を作成します。 – Geinmachi
@LocalBeanをクラスに追加しようとしましたか? –
@Geinmachi、私が理解しているように、Beanがローカルのときはインタフェースを省略できます。また、同じ構造で作業している他のプロジェクトも見てきましたが、そうではないと思います。プロジェクトが別の問題を起こす方法についての詳細が必要な場合は教えてください。 –