This article describes how to use resource as an attribute operation in spring. For your reference, the details are as follows:
1. Configuration file
<?xml version="1.0" encoding="GBK"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<bean
p:res="classpath:book.xml"/>
</beans>
2. Attribute file
<?xml version="1.0" encoding="GBK"?>
< Computer Book list >
< book >
< title > crazy Java handout
Author > Li Gang
< / book >
< book >
< title > lightweight Java EE enterprise application
Author > Li Gang
< / book >
< / computer book list >
Three bean
package org.crazyit.app.service;
import org.springframework.core.io.Resource;
import org.dom4j.io.*;
import org.dom4j.*;
import java.util.*;
public class TestBean
{
private Resource res;
//Setter method of res
public void setRes(Resource res)
{
this.res = res;
}
public void parse()throws Exception
{
//Get simple information about the resource
System.out.println(res.getFilename());
System.out.println(res.getDescription());
//Creating DOM 4J parser based on Sax
SAXReader reader = new SAXReader();
Document doc = reader.read(res.getFile());
//Get root element
Element el = doc.getRootElement();
List l = el.elements();
//Traverses all child elements of the root element
for (Iterator it = l.iterator();it.hasNext() ; )
{
//Each node is a Book node
Element book = (Element)it.next();
List ll = book.elements();
//Traverse all the children of the book node
for (Iterator it2 = ll.iterator();it2.hasNext() ; )
{
Element eee = (Element)it2.next();
System.out.println(eee.getText());
}
}
}
}
Four types of testing
package lee;
import org.springframework.context.*;
import org.springframework.context.support.*;
import org.springframework.core.io.*;
import org.crazyit.app.service.*;
public class SpringTest
{
public static void main(String[] args) throws Exception
{
ApplicationContext ctx = new
ClassPathXmlApplicationContext("beans.xml");
TestBean tb = ctx.getBean("test" , TestBean.class);
tb.parse();
}
}
5. Test results
book.xml
class path resource [book.xml]
Crazy Java handout
Li Gang
Lightweight Java EE enterprise application
Li Gang
For more Java related content, interested readers can view the special topics of this website: introduction and advanced course of spring framework, course of Java data structure and algorithm, summary of Java operating DOM node skills, summary of java file and directory operation skills and summary of Java cache operation skills
I hope that this paper will be helpful to Java programming.