Parsing XML documents using Jdom to simulate spring configuration file parsing

Source: Internet
Author: User

In the Java EE project may involve the use of some framework, recently contacted SSH, take spring to use the configuration file is very important, spring configuration file is an XML file, how does spring read to the configuration file and make dependency injection? Today, let's talk about parsing XML files.

Parse XML file can use Jdom, below I with a small chestnut to say XML file parsing.

1. First download jdom, here I take jdom2.0.6 as an example

2. Next, attach an XML document

<?XML version= "1.0" encoding= "UTF-8"?><Beans>    <BeanID= "U"class= "EDU.NUPT.BBS.USERDAOIMP" />     <BeanID= "Service"class= "Edu.nupt.bbs.UserService">         < Propertyname= "Userdao"ref= "U" />     </Beans>     </Beans>

The code mimics the spring configuration file

3. Define a user class (model) code as follows

 PackageEdu.nupt.bbs; Public classUser {PrivateString ID;  PublicString getId () {returnID; }     Public voidsetId (String id) { This. ID =ID; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }    PrivateString name;}
View Code

4. Define a Userdao interface this is a DAO interface in order to facilitate the experiment mainly provides the adduser and DeleteUser interface

 Package Edu.nupt.bbs;  Public Interface Userdao {    publicvoid  Add ();      Public void Delete ();}

5. Defining a USERDAOIMP implementation of the Userdao interface I don't quite understand why Userdao is written in the form of an interface may be to be compatible on different databases, the specific code is as follows, To make it simple and intuitive to print a piece of text directly from the console in the Add method and delete method

 PackageEdu.nupt.bbs;/*** A Userdao implementation (may be a database corresponding to a Userdao implementation in the actual application) *@authorXiaoysec **/ Public classUserdaoimpImplementsUserdao {@Override Public voidAdd () {//TODO auto-generated Method StubSYSTEM.OUT.PRINTLN ("User Add"); } @Override Public voidDelete () {//TODO auto-generated Method StubSYSTEM.OUT.PRINTLN ("User Delete"); }}
View Code

6. Define the UserService class to implement the user object additions and deletions, the beginning of contact with the Java EE is not very clear why to write so many seemingly unwanted classes, but gradually found that this layered thinking is extremely reasonable, convenient program extension and maintenance.

 PackageEdu.nupt.bbs;/*** A Userdao implementation (may be a database corresponding to a Userdao implementation in the actual application) *@authorXiaoysec **/ Public classUserdaoimpImplementsUserdao {@Override Public voidAdd () {//TODO auto-generated Method StubSYSTEM.OUT.PRINTLN ("User Add"); } @Override Public voidDelete () {//TODO auto-generated Method StubSYSTEM.OUT.PRINTLN ("User Delete"); }}
View Code

The basic work is over, the following is the simulation of spring profile reading, and I modeled the naming method in spring as defined by: Beanfactory and Classpathxmlapplicationcontext

The 7.BeanFactory interface returns an object that we extracted a bean object from beanfactory using the XML id attribute as a parameter. This interface, like his name, can imagine her as a factory. The Bean object is provided to the outside world through the ID parameter.

 Package edu.nupt.bbs.Spring; // returns a bean by ID  Public Interface beanfactory {    public  Object getbean (String ID);}

8.ClassPathXmlApplicationContext

 Packageedu.nupt.bbs.Spring;Importjava.io.IOException;ImportJava.util.HashMap;Importjava.util.List;ImportJava.util.Map;Importorg.jdom2.Document;Importorg.jdom2.Element;Importorg.jdom2.JDOMException;ImportOrg.jdom2.input.SAXBuilder;Importorg.junit.Test;Importedu.nupt.bbs.test.JdomTest; Public classClasspathxmlapplicationcontextImplementsBeanfactory {//for storing bean instance objects    Privatemap<string, object> map =NewHashmap<string, object>(); //used to remove a bean instance object@Override PublicObject Getbean (String id) {//TODO auto-generated Method StubObject o =map.get (ID); returno; }     PublicClasspathxmlapplicationcontext () {Try{saxbuilder SB=NewSaxbuilder (); Document Doc= Sb.build (jdomtest.class. getClassLoader (). getResourceAsStream ("Jdom.xml"));//Constructing Document ObjectsElement root = Doc.getrootelement ();//gets the root element beansList List = Root.getchildren ("Bean");//name all the elements of the bean             for(inti = 0; I < list.size (); i++) {element element=(Element) list.get (i); String ID= Element.getattributevalue ("id");//gets the value of the IDString clazz = Element.getattributevalue ("class");//get the value of class//System.out.println (id + ":" + clazz);                Try{Object o=Class.forName (clazz). newinstance (); Map.put (ID, o);//put the object represented by the ID into the map                } Catch(instantiationexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(illegalaccessexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(ClassNotFoundException e) {//TODO auto-generated Catch blockE.printstacktrace (); }            }        } Catch(jdomexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }    }}
View Code

You need to provide a map object to store the generated bean object as a container, in fact the code above is to complete the XML parsing and the Bean instance object generation, and put the bean instance object in the map, which uses the Java reflection.

<bean id= "U" class= "Edu.nupt.bbs.UserDAOImp"/> This is an object that is stored in the list in the above code, in fact, is to use reflection based on the value of class to generate an instance of the object assigned to u that is userdaoimp u = New Userdaoimp ();

9. Test class

 Packageedu.nupt.bbs.test;Import Staticorg.junit.assert.*;Importorg.junit.Test;ImportEdu.nupt.bbs.User;ImportEdu.nupt.bbs.UserDAO;ImportEdu.nupt.bbs.UserService;Importedu.nupt.bbs.Spring.BeanFactory;ImportEdu.nupt.bbs.Spring.ClassPathXmlApplicationContext; Public classuserservicetest {@Test Public voidaddusertest () {beanfactory bf=NewClasspathxmlapplicationcontext (); Userdao Userdao= (Userdao) Bf.getbean ("U")); UserService Service= (UserService) bf.getbean ("service");        Service.setuserdao (Userdao);    Service.adduser (); }}

Test results

Parsing XML documents using Jdom to simulate spring configuration file parsing

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.