Skip to content

Instantly share code, notes, and snippets.

@antoinesd
Last active December 14, 2016 11:01
Show Gist options
  • Save antoinesd/c51cdbfa4348abaeacc2024551f86e8d to your computer and use it in GitHub Desktop.
Save antoinesd/c51cdbfa4348abaeacc2024551f86e8d to your computer and use it in GitHub Desktop.
Basic Example for CDI-643
package org.jboss.cdi.api.test.injectiontargetsample.frameworkz;
/**
* Class in a legacy framework we don't own.
* instance may even be provided by a container or registry in this framework
*/
public class NotOurClass {
private SomeService service;
// method to call after instance construction to make it valid
public void setService(SomeService service) {
this.service = service;
}
//perform operations with service
}
package org.jboss.cdi.api.test.injectiontargetsample.frameworkz;
/**
* some service in Framework Z
*/
public interface SomeService {
}
package org.jboss.cdi.api.test.injectiontargetsample;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.literal.InjectLiteral;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.inject.spi.InjectionTarget;
import javax.enterprise.inject.spi.InjectionTargetFactory;
import javax.inject.Inject;
import org.jboss.cdi.api.test.injectiontargetsample.frameworkz.NotOurClass;
@ApplicationScoped
public class IocForFrameworkZ {
private CreationalContext<NotOurClass> nocc;
private final InjectionTarget<NotOurClass> it;
@Inject
public IocForFrameworkZ(BeanManager bm) {
nocc = bm.createCreationalContext(null);
InjectionTargetFactory<NotOurClass> itf = bm.getInjectionTargetFactory(bm.createAnnotatedType(NotOurClass.class));
itf.configure().filterMethods( m -> m.getJavaMember().getName().equals("setService")).findFirst().get().add(InjectLiteral.INSTANCE);
it = itf.createInjectionTarget(null);
}
public NotOurClass injectServiceInNotOurClass(NotOurClass noc) {
it.inject(noc, nocc);
return noc;
}
}
@antoinesd
Copy link
Author

antoinesd commented Dec 14, 2016

Injecting in unmanaged instances coming from a 3rd party framework.
Could easily adapted to perform injection in a producer as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment