Spring learning notes-Principles of Sprin Bean Management
When we use Spring
Configuration allows you to operate the attributes and methods of the Bean. How does Spring implement it? Let's implement this process by ourselves.
First, I create a Bean management class MyClassPathXMLApplicationContext. java by Simulating Spring naming. The Code is as follows:
// Custom container public class MyClassPathXMLApplicationContext {private List
BeanDefines = new ArrayList
(); Private Map
Singletons = new HashMap
(); Public MyClassPathXMLApplicationContext (String filename) {// 1. Read the configuration file this. readXML (filename); // 2. instantiate Bean this. instanceBeans ();}/*** instantiate bean */private void instanceBeans () {for (BeanDefinition beanDefinition: beanDefines) {try {if (beanDefinition. getClassName ()! = Null &&! "". Equals (beanDefinition. getClassName (). trim () singletons. put (beanDefinition. getId (), Class. forName (beanDefinition. getClassName ()). newInstance ();} catch (Exception e) {e. printStackTrace () ;}}/ *** read xml configuration file * @ param filename */private void readXML (String filename) {SAXReader saxReader = new SAXReader (); document document = null; try {URL xmlpath = this. getClass (). getClassLoader (). getResource (filename); document = saxReader. read (xmlpath); Map
NsMap = new HashMap
(); NsMap. put ("ns", "http://www.springframework.org/schema/beans"); // Add the namespace XPath xsub = document. createXPath ("// ns: beans/ns: bean"); // create the beans/bean query path xsub. setNamespaceURIs (nsMap); // sets the namespace List
Beans = xsub. selectNodes (document); // obtain all bean nodes under the document for (Element element: beans) {String id = element. attributeValue ("id"); // obtain the id attribute value String clazz = element. attributeValue ("class"); // get the class attribute value BeanDefinition beanDefine = new BeanDefinition (id, clazz); beanDefines. add (beanDefine) ;}} catch (Exception e) {e. printStackTrace () ;}}/*** get bean instance * @ param beanName * @ return */public Object getBean (String beanName) {return this. si? gletons. get (beanName );}}
The configuration file is as follows:
Let's test it:
public class SpringTest { @BeforeClass public static void setUpBeforeClass() throws Exception { } @Test public void instanceSpring(){ MyClassPathXMLApplicationContext ctx = new MyClassPathXMLApplicationContext("beans.xml"); PersonService personService = (PersonService)ctx.getBean("personService"); personService.save(); }}
Running successful