简体   繁体   中英

Weld dependency injection issues

I have a POJO that I create to hold context for the client of a RESTful API, similar to this (actual class is proprietary).

class MyPOJO {

    @Inject
    public AnInjectedInterface obj1;

    @Inject
    public AnotherInjectedInterface obj2;

    public String data1;

    public int data2;

    public long data3;

}

I want to use it thusly:

MyPOJO pojo = new MyPOJO();
pojo.data1 = "something";
pojo.data2 = 43;
pojo.data3 = 2875640;
pojo.obj1.someFunction();
pojo.obj2.anotherFunction("something");

If I do this, obj1 and obj2 are always null. These interfaces are used elsewhere in non-POJO classes and are injected correctly. They are dependent objects and the code above appears in an application scoped bean, so I can't inject the POJO there.

My question is this; is DI not available in objects not instantiated by the container? If so, is there any way to tell the container to instantiate my dependent POJO in an application scoped bean complete with dependencies? If not, what am I doing wrong? My container is Wildfly 11.

Thank you.

You're doing it wrong. Instead of using MyPOJO pojo = new MyPOJO(); you just @Inject MyPOJO pojo into whichever ( bean ) class you want to use it from.

CDI/Weld does the creation for you and while at it, it will resolve all the inner dependencies ( obj1 and obj2 in your case).

I see you have edited the question, so here are other bits of the answers.

First of all you can inject @Dependent into @ApplicationScoped and if you need multiple instances, you could leverage Instance<MyPOJO> and on each get() you should be getting new instance. But note that you will need to make sure you dispose of these objects as well!

is DI not available in objects not instantiated by the container?

By default, CDI will not handle it in any way. You can however perform injection into such object yourself. To stay precise, the object you are injecting into will be handled as an InjectionTarget and you will need BeanManager to do that. Here is roughly how ( not a copy-paste code ):

BeanManager beanManager; // assuming you have obtained BM somehow
CreationalContext<Object> ctx = beanManager.createCreationalContext(null);
InjectionTarget<MyPOJO> injectionTarget = beanManager
                    .getInjectionTargetFactory(beanManager.createAnnotatedType(MyPOJO.class)).createInjectionTarget(null);
injectionTarget.inject(myPojoInstance, ctx);
creationalContext = ctx; // store ctx so you can later on use it to dispose of the dependent instance!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM