
上QQ阅读APP看书,第一时间看更新
The injection target
Here is a sample to use manual injection through the inject.spi API:
BeanManager beanManager = current().getBeanManager();
CDI uses an AnnotatedType object to read annotations of a class:
AnnotatedType<String> type = beanManager.createAnnotatedType(String.class);
The extension uses an InjectionTarget to delegate instantiation, dependency injection, and lifecycle callbacks to the CDI container:
InjectionTarget<String> it = beanManager.createInjectionTarget(type);
Each instance needs its own CDI CreationalContext:
CreationalContext<String> ctx = beanManager.createCreationalContext(null);
Call the constructor:
String instance = it.produce(ctx);
Then call initializer methods and perform field injection:
it.inject(instance, ctx);
Here we call the the @PostConstruct method:
it.postConstruct(instance);
The instance is created; now we can destroy the framework component instance and clean up dependent objects.
Call the @PreDestroy method:
it.preDestroy(instance);
It is now safe to discard the instance:
it.dispose(instance);
Clean up dependent objects:
ctx.release();