dynamic injection with beanmanager
tomathome Apr 11, 2012 5:50 AM//
//Qualifier Class
//
{code}
@Qualifier
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({METHOD, FIELD, ElementType.TYPE, PARAMETER})
public @interface Car {
@Nonbinding
String name() type "";
}
{code}
//
// Bean Class
//
{code}
public class CarInst {
private String test = "initial";
public CarInst(String name) {
test = name;
}
public String getTest() {
return test;
}
}
{code}
//
//Producer Class
//
public class CarInstProducer {
@Produces @Car()
public CarInst produce(InjectionPoint ip) {
for( Annotation qualifier : ip.getQualifiers() ) {
if( qualifier instanceof Car ) {
Car carType = (Car)qualifier;
return new CarInst(carType.type());
}
}
return null;
}
}
//
// Car literal class
//
public abstract class CarLiteral extends AnnotationLiteral<Car> implements Car {
private static final long serialVersionUID = 742218573198647647L;
public String type() {
return "Value from Literal";
}
}
// Static Injection is working correctly.
// The 'InjectionPoint ip' in producer class is not null,
// so the type() can be retrieved from the ip.
@Inject @Car(type="familly")
CarInst carInst;
// The test main method.
// Try to inject CarInst dynamically by the use of beanmanager.
// The producer method throw NullPointerException, because InjectionPoint is null.
// the type() cannot be retieved from ip.
main() {
CarLiternal carLiteral = new CarLiteral();
Set<Bean<?>> beans = beanManager.getBeans(CarInst.class, carLiteral);
Bean<?> bean = beans.iterator().next();
CreationalContext<?> creationalContext = beanManager.createCreationalContext(bean);
// The producer method will be executed here. NullPointer exception.
getReference(bean, CarImpl.class, creationalContext);
}
Somebody know, how to use beanmanager to inject the CarImple dynamically and put somehow the type() dynamically,
so that the producer method can retrieve it from InjectionPoint ip parameter?