1 16 package org.directwebremoting.spring; 17 18 import java.util.ArrayList ; 19 import java.util.Arrays ; 20 import java.util.Collection ; 21 import java.util.Collections ; 22 import java.util.List ; 23 import java.util.Map ; 24 25 import org.directwebremoting.Container; 26 import org.directwebremoting.impl.DefaultContainer; 27 import org.directwebremoting.util.Logger; 28 import org.springframework.beans.BeansException; 29 import org.springframework.beans.factory.BeanFactory; 30 import org.springframework.beans.factory.BeanFactoryAware; 31 import org.springframework.beans.factory.InitializingBean; 32 import org.springframework.beans.factory.ListableBeanFactory; 33 import org.springframework.util.ClassUtils; 34 35 42 public class SpringContainer extends DefaultContainer implements Container, BeanFactoryAware, InitializingBean 43 { 44 47 public void setBeanFactory(BeanFactory beanFactory) throws BeansException 48 { 49 this.beanFactory = beanFactory; 50 } 51 52 public void addParameter(Object askFor, Object valueParam) 53 throws InstantiationException , IllegalAccessException { 54 try { 55 Class clz = ClassUtils.forName((String )askFor); 56 if (log.isDebugEnabled()) { 57 log.debug("trying to resolve the following class from the Spring bean container: " + clz.getName()); 58 } 59 60 Map beansOfType = ((ListableBeanFactory)beanFactory).getBeansOfType(clz); 61 if (log.isDebugEnabled()) { 62 log.debug("beans: " + beansOfType + " - " + beansOfType.size()); 63 } 64 if (beansOfType.size() == 0) { 65 log.debug("adding parameter the normal way"); 66 super.addParameter(askFor, valueParam); 67 } else if (beansOfType.size() > 1) { 68 throw new InstantiationException ("multiple beans of type '" + clz.getName() + "' were found in the spring configuration"); 70 } else { 71 this.beans.put(askFor, beansOfType.values().iterator().next()); 72 } 73 } catch (ClassNotFoundException e) { 74 super.addParameter(askFor, valueParam); 75 } 76 } 77 78 81 public Object getBean(String id) 82 { 83 Object reply; 84 try { 85 reply = beanFactory.getBean(id); 86 } 87 catch (BeansException ex) 88 { 89 reply = super.getBean(id); 91 } 92 93 return reply; 94 } 95 96 99 public Collection getBeanNames() 100 { 101 List names = new ArrayList (); 102 103 if (beanFactory instanceof ListableBeanFactory) 105 { 106 ListableBeanFactory listable = (ListableBeanFactory) beanFactory; 107 names.addAll(Arrays.asList(listable.getBeanDefinitionNames())); 108 } 109 else 110 { 111 log.warn("List of beanNames does not include Spring beans since your BeanFactory is not a ListableBeanFactory."); 112 } 113 114 names.addAll(super.getBeanNames()); 116 117 return Collections.unmodifiableCollection(names); 118 } 119 120 123 public void afterPropertiesSet() throws Exception 124 { 125 callInitializingBeans(); 126 } 127 128 131 protected BeanFactory beanFactory; 132 133 136 private static final Logger log = Logger.getLogger(SpringContainer.class); 137 } 138 | Popular Tags |