jake
jake

Reputation: 51

Search EJB container for implementations of a specific interface

I am attempting to create an injection style mechanism to tie EE5 to another framework that does not support EJB injection. Currently I am using a custom annotation and a naming convention to look up the EJB in JNDI:

    @ContainerResource
private LocalListener listener; 

@Initialize
public void init(){
    new Injection<InjectionAction>().inject(this);
}

The injection class:

public class Injection<T> {

public void inject(T clazz) {
    for(Field field : clazz.getClass().getDeclaredFields()){
        if(field.isAnnotationPresent(ContainerResource.class)){
            Object resource = findResource(field);
            try {
                field.setAccessible(true);
                field.set(clazz, resource);
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }


}

private Object findResource(Field field) {
    Object resource = null;
    try {
        InitialContext ic = new InitialContext();
        resource =  ic.lookup(field.getType().getSimpleName()+ "Impl/local");

    } catch (NamingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return resource;



}

}

I would like to find a more robust method, that does not rely on a naming convention, to search the container for an EJB based on its local interface.

Upvotes: 0

Views: 170

Answers (1)

Gabriel Aramburu
Gabriel Aramburu

Reputation: 2981

I don't know if I'm understanding your problem, but if you want to look up an object in a JNDI registry the only way is trought his name, therefore, you have to know the name or to rely in a name convention.

EJB injection internally is implemented using JNDI and also rely in a name convention. If you use the annotation @EJB without parameters the container will look up the object using the local interface name or explicitly you can to indicate the used binding name with @EJB (name="myBeanJNDIbindigName")

Upvotes: 1

Related Questions