/* * Copyright 2005-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wamblee.cdi; import javax.enterprise.context.spi.CreationalContext; import javax.enterprise.inject.spi.AnnotatedType; import javax.enterprise.inject.spi.BeanManager; import javax.enterprise.inject.spi.InjectionTarget; import org.wamblee.inject.Injector; /** * Class encapsulating bean injection into a specific non-contextual object of a * given class. * * @author Erik Brakkee */ public class CdiInjector implements Injector { private Class clazz; private InjectionTarget target; private CreationalContext ctx; /** * Constructs the injector. * * @param aMgr * Bean manager. * @param aClass * Class to analyse for injection. */ public CdiInjector(BeanManager aMgr, Class aClass) { clazz = aClass; AnnotatedType type = aMgr.createAnnotatedType(aClass); target = aMgr.createInjectionTarget(type); ctx = aMgr.createCreationalContext(null); } /* * (non-Javadoc) * * @see org.wamblee.cdi.Injector#inject(java.lang.Object) */ public void inject(Object aComponent) { if (aComponent != null) { if (!clazz.isInstance(aComponent)) { throw new RuntimeException("Object '" + aComponent + "' is of type " + aComponent.getClass().getName() + " but expected " + clazz.getName()); } target.inject(aComponent, ctx); } } }