2 * Copyright 2005-2010 the original author or authors.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package org.wamblee.test.inject;
18 import javax.persistence.EntityManager;
20 import org.wamblee.inject.Injector;
21 import org.wamblee.inject.InjectorFactory;
22 import org.wamblee.inject.InjectorBuilder;
23 import org.wamblee.test.persistence.JpaBuilder;
27 * The test injector factory provides dependency injection of a contextual entity manager
28 * using the support/inject mini framework. It supports dependency injection of fields
29 * annoted with <code>@PersistenceContext</code>. It only supports one persistence context
30 * at the moment. This injector can be easily used together with {@link JpaBuilder#getContextualEntityManager()}
31 * for obtaining an entity manager in unit test.
35 * The reason it is needed is because standard injection mechanisms (such as weld CDI) do not support
36 * entity manager injection in a Java SE environment out of the box.
40 * To use it, construct the factory using one of the available constructors and set
41 * <code>InjectorBuilder.setInjectorFactory(InjectorFactory)</code>.
44 * @author Erik Brakkee
47 public class JavaEETestInjectorFactory implements InjectorFactory {
49 private EntityManager entityManager;
50 private InjectorFactory delegate;
53 * Constructs the factory.
54 * @param aEntityManager Contextual entity manager to inject.
55 * @param aInjectorFactory Injector factory to delegate to.
57 public JavaEETestInjectorFactory(EntityManager aEntityManager, InjectorFactory aInjectorFactory) {
58 entityManager = aEntityManager;
59 delegate = aInjectorFactory;
63 * Constructs the factory with the default injector factory obtained from
64 * {@link InjectorBuilder#getInjector()}.
65 * @param aEntityManager Contextual entity manager to inject.
67 public JavaEETestInjectorFactory(EntityManager aEntityManager) {
68 this(aEntityManager, getDefaultInjectorFactory());
71 private static InjectorFactory getDefaultInjectorFactory() {
72 InjectorBuilder.setInjectorFactory(null);
73 return InjectorBuilder.getInjectorFactory();
77 public Injector create(Class aClass) {
78 return new JavaEETestInjector(aClass, entityManager, delegate