简体   繁体   中英

CDI bean is not injected but can be looked up

So, I wrote an extension which registers bean I am trying to create. The bean gets scanned by CDI and I can get it using:

MyInterface myInterface = CDI.current().select(MyInterface.class).get();

And I can then access myInterface.myMethod();

However, when I try to inject my bean using:

@Inject
@MyBean
MyInterface myInterface;

it is not injected and is null .

What I want to achieve is that I specify interface, which defines some methods,then my code generates instance of this interface and returns proxy of interface type:

// defined interface
@RegisterAsMyBean
interface MyInterface {
    void myMethod();
}

// usage in code:
@Inject
@MyBean
MyInterface myInterface;

I declared my bean like this:

public class MyExtension implements Extension {
    public void register(@Observes @WithAnnotations(RegisterAsMyBean.class) ProcessAnnotatedType<?> aType) {
        Class<?> typeDef = aType.getAnnotatedType().getJavaClass();

        if(typeDef.isInterface()) {
            proxyTypes.add(typeDef);
            aType.veto();
        }
    }
}

public class BeanCreator implements Bean<Object> {
    @Override
    public Object create(CreationalContext<Object> creationalContext) {
        // my instance building logic
    }
    // ... other overriden methods
}

Also in META-INF/services/javax.enterprise.inject.spi.Extension I put reference to MyExtension

The problem was in bean creation lifecycle - i was trying to create bean in processAnnotatedType cycle, while I should have done that during afterBeanDiscovery cycle.

After moving my bean creation logic to appropriate cycle the bean is created and properly injected.

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