I will look at @Inject as this seems like the solution I am looking for, but it did not work when I tried. I'm sure something is missing, but I tried for a while and will not go anywhere. A difficult time led me to implement the helper class below, which I thought I would lay out for those who would use them if they had similar problems.
Thanks for answers.
public class InjectionHelper {
private static final String DEPENDENCY_SEPERATOR = "/";
private static Logger logger = Logger.getLogger(InjectionHelper.class);
private static Map<Class<?>, Object> dependencies = null;
private static List<Object> dependenciesList = null;
private static Context baseContext = null;
public static final <T> T injectDependency(Class<T> dependencyClass){
if(dependenciesList == null){
dependenciesList = new ArrayList<Object>();
dependencies = new HashMap<Class<?>, Object>();
try{
baseContext = new InitialContext();
populateDependencies(baseContext, new Stack<String>());
}
catch(Exception e){
logger.error("Error populating dependencies", e);
}
}
if(dependencies.containsKey(dependencyClass)){
return (T)dependencies.get(dependencyClass);
}
for(Object o: dependenciesList){
if(dependencyClass.isInstance(o)){
dependencies.put(dependencyClass, o);
return (T)o;
}
}
return null;
}
private static final void populateDependencies(Context ctx, Stack<String> lookupNameStack) {
try {
NamingEnumeration<Binding> list = ctx.listBindings("");
while (list.hasMore()) {
Binding item = list.next();
String lookupName = item.getName();
Object objectBinding = item.getObject();
if(objectBinding instanceof JavaGlobalJndiNamingObjectProxy){
Iterator<String> lookupNameIterator = lookupNameStack.iterator();
String lookupPrefix = "";
while(lookupNameIterator.hasNext()){
lookupPrefix += lookupNameIterator.next();
}
try{
Object obj = baseContext.lookup(lookupPrefix+lookupName);
dependenciesList.add(obj);
logger.info("Found [" + obj.getClass() + "] Lookup [" + lookupPrefix + lookupName +"]");
}
catch(Exception e){
logger.info("Failed to find Lookup [" + lookupPrefix+lookupName + "]", e);
}
}
lookupNameStack.push(lookupName+DEPENDENCY_SEPERATOR);
if (objectBinding instanceof Context) {
populateDependencies((Context) objectBinding, lookupNameStack);
}
lookupNameStack.pop();
}
} catch (NamingException ex) {
logger.info("JNDI failure: ", ex);
}
}
}
James source
share