1 10 11 package org.nanocontainer.script.groovy.buildernodes; 12 13 import java.util.Map ; 14 15 import org.nanocontainer.NanoContainer; 16 import org.picocontainer.MutablePicoContainer; 17 import org.nanocontainer.script.NanoContainerMarkupException; 18 import java.util.Iterator ; 19 import org.codehaus.groovy.runtime.InvokerHelper; 20 21 31 public class BeanNode extends AbstractBuilderNode { 32 33 36 public static final String NODE_NAME = "bean"; 37 38 41 public static final String BEAN_CLASS = "beanClass"; 42 43 44 47 public BeanNode() { 48 super(NODE_NAME); 49 } 50 51 public Object createNewNode(Object current, Map attributes) { 52 MutablePicoContainer pico = ((NanoContainer) current).getPico(); 53 Object bean = createBean(attributes); 54 pico.registerComponentInstance(bean); 55 return bean; 56 } 57 58 59 64 protected Object createBean(final Map attributes) { 65 Class type = (Class ) attributes.remove(BEAN_CLASS); 66 if (type == null) { 67 throw new NanoContainerMarkupException("Bean must have a beanClass attribute"); 68 } 69 try { 70 Object bean = type.newInstance(); 71 for (Iterator iter = attributes.entrySet().iterator(); iter.hasNext();) { 73 Map.Entry entry = (Map.Entry ) iter.next(); 74 String name = entry.getKey().toString(); 75 Object value = entry.getValue(); 76 InvokerHelper.setProperty(bean, name, value); 77 } 78 return bean; 79 } catch (IllegalAccessException e) { 80 throw new NanoContainerMarkupException("Failed to create bean of type '" + type + "'. Reason: " + e, e); 81 } catch (InstantiationException e) { 82 throw new NanoContainerMarkupException("Failed to create bean of type " + type + "'. Reason: " + e, e); 83 } 84 } 85 86 93 public void validateScriptedAttributes(Map specifiedAttributes) throws NanoContainerMarkupException { 94 if (!specifiedAttributes.containsKey(BEAN_CLASS)) { 95 throw new NanoContainerMarkupException("Attribute " + BEAN_CLASS + " is required."); 96 } 97 98 } 100 } 101 | Popular Tags |