Java中中spring读取配置文件的几种方法示例读取配置文件的几种方法示例
本篇文章中主要介绍了Java中spring读取配置文件的几种方法示例,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。
Spring读取配置读取配置XML文件分三步:文件分三步:
一.新建一个Java Bean:
package springdemo;
public class HelloBean {
private String helloWorld;
public String getHelloWorld() {
return helloWorld;
}
public void setHelloWorld(String helloWorld) {
this.helloWorld = helloWorld;
}
}
二.构建一个配置文件bean_config.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd" >
<beans>
<bean id="helloBean" class="springdemo.HelloBean">
<property name="helloWorld">
<value>Hello!chb!</value>
</property>
</bean>
</beans>
三.读取配置文件:
1.利用ClassPathXmlApplicationContext:
ApplicationContext context = new ClassPathXmlApplicationContext("bean_config.xml");
//这种用法不够灵活,不建议使用。
HelloBean helloBean = (HelloBean)context.getBean("helloBean");
System.out.println(helloBean.getHelloWorld());
ClassPathXmlApplicationContext实现了接口ApplicationContext,ApplicationContext实现了BeanFactory。其通过jdom进行XML配置文件的读
取,并构建实例化Bean,放入容器内。
public interface BeanFactory {
public Object getBean(String id);
}
//实现类ClassPathXmlApplicationContext
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
public class ClassPathXmlApplicationContext implements BeanFactory {
private Map<String , Object> beans = new HashMap<String, Object>();
//(IOC:Inverse of Control/DI:Dependency Injection)
public ClassPathXmlApplicationContext() throws Exception {
SAXBuilder sb=new SAXBuilder();
Document doc=sb.build(this.getClass().getClassLoader().getResourceAsStream("beans.xml")); //构造文档对象
Element root=doc.getRootElement(); //获取根元素HD
List list=root.getChildren("bean");//取名字为disk的所有元素
for(int i=0;i<list.size();i++){
Element element=(Element)list.get(i);
String id=element.getAttributeValue("id");
String clazz=element.getAttributeValue("class");
Object o = Class.forName(clazz).newInstance();
System.out.println(id);
System.out.println(clazz);
beans.put(id, o);
for(Element propertyElement : (List<Element>)element.getChildren("property")) {
String name = propertyElement.getAttributeValue("name"); //userDAO
String bean = propertyElement.getAttributeValue("bean"); //u
Object beanObject = beans.get(bean);//UserDAOImpl instance
String methodName = "set" + name.substring(0, 1).toUpperCase() + name.substring(1);
System.out.println("method name = " + methodName);
Method m = o.getClass().getMethod(methodName, beanObject.getClass().getInterfaces()[0]);
m.invoke(o, beanObject);
}
评论0
最新资源