Description:java
Mock up how spring container initializes the beans from property file.spring
A simple mock-up. Just consider that no other property files imported.apache
package com.jesse.spring.containermockup.utils; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.XPath; import org.dom4j.io.SAXReader; import com.jesse.spring.containermockup.model.BeanDefinition; public class MockupClassPathXMLApplicationContext { private List<BeanDefinition> beanDefinitions = new ArrayList<BeanDefinition>(); private Map<String, Object> singletons = new HashMap<String, Object>(); private static final Logger logger = Logger.getLogger(MockupClassPathXMLApplicationContext.class); public MockupClassPathXMLApplicationContext(String filename) { this.readXML(filename); initBeans(); logger.info("beanDefinitions.size == >> " + beanDefinitions.size()); } public void initBeans() { for(BeanDefinition beanDefinition : beanDefinitions) { try { singletons.put(beanDefinition.getId(), Class.forName(beanDefinition.getClassName()).newInstance()); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { e.printStackTrace(); } } } public Object getBean(String name) { if(singletons.size() > 0) { return singletons.get(name); } return null; } public void readXML(String filename) { try { SAXReader saxReader = new SAXReader(); URL xmlPath = this.getClass().getClassLoader().getResource(filename); Document document = saxReader.read(xmlPath); Map<String,String> nsMap = new HashMap<String,String>(); nsMap.put("ns", "http://www.springframework.org/schema/beans"); XPath xsub = document.createXPath("//ns:beans/ns:bean"); xsub.setNamespaceURIs(nsMap); @SuppressWarnings("unchecked") List<Element> beans = xsub.selectNodes(document); for(Element element : beans) { String id = element.attributeValue("id"); String clazz = element.attributeValue("class"); BeanDefinition beanDefinition = new BeanDefinition(id, clazz); beanDefinitions.add(beanDefinition); } } catch (Exception e) { e.printStackTrace(); } } }