Skip to content

Instantly share code, notes, and snippets.

@hasalex
Created January 31, 2013 06:28
Show Gist options
  • Save hasalex/4680770 to your computer and use it in GitHub Desktop.
Save hasalex/4680770 to your computer and use it in GitHub Desktop.
Custom InjectionProvider that injects EJBs in JSF 1.2 managed beans. Helpful on my JBoss AS 7.1.3 where JSF 1.2 isn't fully integrated.
public class CustomInjectionProvider implements InjectionProvider {
public static final String ROOT_NAME = "java:app/TestJbossEJB-0.0.1-SNAPSHOT/";
public void inject(Object o) throws InjectionProviderException {
Field[] fields = o.getClass().getDeclaredFields();
try {
for (Field field : fields) {
if (field.getAnnotation(EJB.class) != null) {
field.setAccessible(true);
field.set(o, getBean(field.getType()));
}
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NamingException e) {
e.printStackTrace();
}
}
public void invokePreDestroy(Object o) throws InjectionProviderException {
}
public void invokePostConstruct(Object o) throws InjectionProviderException {
}
private Object getBean(Class<?> type) throws NamingException {
Context context = (Context) new InitialContext().lookup(ROOT_NAME);
NamingEnumeration<Binding> bindings = context.listBindings("");
while (bindings.hasMoreElements()) {
Binding binding = bindings.nextElement();
Object object = binding.getObject();
if (type.isAssignableFrom(object.getClass())) {
return object;
}
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment