Java Simulation Spring

Source: Internet
Author: User

I. Overview

1. Goal: Simulate Spring's IOC

2. Use of the knowledge Point: Using Jdom XPath to read the XML file, reflection

Second, the following documents are available:

1.applicationcontext.xml

<?xml version= "1.0" encoding= "UTF-8"?><beans>  <bean id= "vehicle" class= " Com.tong.spring.factory.Car ">  </bean></beans>

  

2.beanfactory.java

Public interface Beanfactory {Object Getbean (String ID);}

  

3.classpathxmlapplicationcontext.java

public class Classpathxmlapplicationcontext implements Beanfactory{private map<string, object> container = new Hashmap<string, object> ();p ublic classpathxmlapplicationcontext (String fileName) {//Read XML file Saxbuilder SB = new Saxbuilder ();D ocument doc;try {//doc = Sb.build (This.getclass (). getClassLoader (). getResourceAsStream (FileName)); doc = Sb.build (fileName); Element root = Doc.getrootelement (); List List = Xpath.selectnodes (Root, "/beans/bean"); for (int i = 0; i < list.size (); i++) {Element element = (Element) L Ist.get (i); String id = element.getattributevalue ("id"); String clazz = Element.getattributevalue ("class");//Use reflection to generate an example and then load the container object o = Class.forName (clazz). newinstance (); Container.put (ID, o);}} catch (Exception e) {e.printstacktrace ();}} @Overridepublic Object Getbean (String ID) {return container.get (ID);}}

  

4.movable.java

public interface Movable {void run ();

  

5.car.java

Public class Car implements movable {public void run () {System.out.println ("Car running .....");}}

 

6.test.java

public class Test {@org. junit.testpublic void Test () {Beanfactory factory = new Classpathxmlapplicationcontext (" Applicationcontext.xml "); Object o = Factory.getbean (" vehicle "); Movable m = (movable) o;m.run ();}}

  

Operation Result:

Java Simulation Spring

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.