博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java设计模式——工厂模式——模拟Spring
阅读量:4030 次
发布时间:2019-05-24

本文共 6164 字,大约阅读时间需要 20 分钟。

模拟Spring读取Properties文件

转自:http://www.cnblogs.com/shamgod/p/4586971.html

一、目标:读取配置文件properties文件,获得类名来生成对象

二、类

1.Movable.java

1
2
3
public 
interface 
Movable {
    
void 
run();
}

  

2.Car.java

1
2
3
4
5
6
7
public 
class 
Car 
implements 
Movable {
 
    
public 
void 
run() {
        
System.out.println(
"Car running..............."
);
    
}
     
}

  

3.spring.properties

PS:"="两边不能有空格

1
vechileType=com.tong.spring.factory.Car

  

4.Test.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public 
class 
Test {
     
    
@org
.junit.Test
    
public 
void 
test() {
         
        
//读取properties文件,获得类名来生成对象
        
Properties pros = 
new 
Properties();
         
        
try 
{
            
//1.读取要实例化的类名
            
pros.load(Test.
class
.getClassLoader().getResourceAsStream(
"com/tong/spring/factory/spring.properties"
));
            
String vechileType = pros.getProperty(
"vechileType"
);
             
            
//2.利用反射装载类及用newInstance()实例化类
            
Object o = Class.forName(vechileType).newInstance();
            
Movable m = (Movable)o;
            
m.run();
        
catch 
(Exception e) {
            
e.printStackTrace();
        
}
    
}
}

  

5.运行结果:

 

 

6.若改成spring读取xml文件,则spring配置好后,增加applicationContext.xml

1
2
3
4
5
6
7
8
9
10
11
12
<?xml version=
"1.0" 
encoding=
"UTF-8"
?>
<beans xmlns=
"http://www.springframework.org/schema/beans"
       
xmlns:xsi=
"http://www.w3.org/2001/XMLSchema-instance"
       
xsi:schemaLocation="http:
//www.springframework.org/schema/beans
           
http:
//www.springframework.org/schema/beans/spring-beans-3.0.xsd">
 
  
<bean id=
"vehicle" 
class
=
"com.tong.spring.factory.Car"
>
  
</bean>
 
  
<!-- more bean definitions go here -->
 
</beans>

  

7.Test.java改为如下

1
2
3
4
5
6
7
8
9
10
11
public 
class 
Test {
     
    
@org
.junit.Test
    
public 
void 
test() {
         
        
BeanFactory factory = 
new 
ClassPathXmlApplicationContext(
"applicationContext.xml"
);
        
Object o = factory.getBean(
"vehicle"
);
        
Movable m = (Movable)o;
        
m.run();
    
}
}

用Jdom模拟Spring

转自:http://www.cnblogs.com/shamgod/p/4587387.html

 一、概述

1.目标:模拟Spring的Ioc

2.用到的知识点:利用jdom的xpath读取xml文件,反射

 

二、有如下文件:

1.applicationContext.xml

1
2
3
4
5
<?xml version=
"1.0" 
encoding=
"UTF-8"
?>
<beans>
  
<bean id=
"vehicle" 
class
=
"com.tong.spring.factory.Car"
>
  
</bean>
</beans>

  

2.BeanFactory.java

1
2
3
public 
interface 
BeanFactory {
    
Object getBean(String id);
}

  

3.ClassPathXmlApplicationContext.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
public 
class 
ClassPathXmlApplicationContext 
implements 
BeanFactory{
     
    
private 
Map<String, Object> container = 
new 
HashMap<String, Object>();
 
    
public 
ClassPathXmlApplicationContext(String fileName) {
         
        
//读取xml文件
        
SAXBuilder sb = 
new 
SAXBuilder();
        
Document doc;
        
try 
{
            
//doc = sb.build(fileName);
            
//Test.java要改为BeanFactory factory = new ClassPathXmlApplicationContext("com/tong/spring/factory/applicationContext.xml");
            
//否则付出现“java.net.MalformedURLException”
            
doc = sb.build(
this
.getClass().getClassLoader().getResourceAsStream(fileName));
            
Element root = doc.getRootElement();
            
List list = XPath.selectNodes(root, 
"/beans/bean"
);
 
            
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();
                
container.put(id, o);
            
}
        
catch 
(Exception e) {
            
e.printStackTrace();
        
}
 
    
}
 
    
@Override
    
public 
Object getBean(String id) {
        
return 
container.get(id);
    
}
 
}

  

4.Movable.java

1
2
3
public 
interface 
Movable {
    
void 
run();
}

  

5.Car.java

1
2
3
4
5
6
7
public 
class 
Car 
implements 
Movable {
 
    
public 
void 
run() {
        
System.out.println(
"Car running..............."
);
    
}
     
}

 

6.Test.java 

 

1
2
3
4
5
6
7
8
9
10
11
12
public 
class 
Test {
     
    
@org
.junit.Test
    
public 
void 
test() {
         
        
//BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml");
        
BeanFactory factory = 
new 
ClassPathXmlApplicationContext(
"com/tong/spring/factory/applicationContext.xml"
);
        
Object o = factory.getBean(
"vehicle"
);
        
Movable m = (Movable)o;
        
m.run();
    
}
}

 

  

 

  

运行结果:

JDOM 2操作XML:http://www.studytrails.com/java/xml/jdom2/java-xml-jdom2-xpath/

package com.studytrails.xml.jdom;  import java.io.IOException;import java.util.List; import org.jdom2.Document;import org.jdom2.Element;import org.jdom2.JDOMException;import org.jdom2.Namespace;import org.jdom2.filter.Filters;import org.jdom2.input.SAXBuilder;import org.jdom2.xpath.XPathExpression;import org.jdom2.xpath.XPathFactory;  public class XPathExample2 {    private static String xmlSource = "http://feeds.bbci.co.uk/news/technology/rss.xml?edition=int";      public static void main(String[] args) throws JDOMException, IOException {          // read the XML into a JDOM2 document.        SAXBuilder jdomBuilder = new SAXBuilder();        Document jdomDocument = jdomBuilder.build(xmlSource);          // use the default implementation        XPathFactory xFactory = XPathFactory.instance();        // System.out.println(xFactory.getClass());          // select all links        XPathExpression
expr = xFactory.compile("//link", Filters.element()); List
links = expr.evaluate(jdomDocument); for (Element linkElement : links) { System.out.println(linkElement.getValue()); } // select all links in image element expr = xFactory.compile("//image/link", Filters.element()); List
links2 = expr.evaluate(jdomDocument); for (Element linkElement : links2) { System.out.println(linkElement.getValue()); } // get the media namespace Namespace media = jdomDocument.getRootElement().getNamespace("media"); // find all thumbnail elements from the media namespace where the // attribute widht has a value > 60 expr = xFactory.compile("//media:thumbnail[@width>60.00]", Filters.element(), null, media); // find the first element in the document and get its attribute named 'url' System.out.println(expr.evaluateFirst(jdomDocument).getAttributeValue("url")); // find the child element of channel whose name is title. find the // descendant of item with name title. Element firstTitle = xFactory.compile("//channel/child::item/descendant::title", Filters.element()).evaluateFirst(jdomDocument); System.out.println(firstTitle.getValue()); } }

你可能感兴趣的文章
[互联网学习]如何提高网站的GooglePR值
查看>>
[关注大学生]求职不可不知——怎样的大学生不受欢迎
查看>>
[关注大学生]读“贫困大学生的自白”
查看>>
[互联网关注]李开复教大学生回答如何学好编程
查看>>
[关注大学生]李开复给中国计算机系大学生的7点建议
查看>>
[关注大学生]大学毕业生择业:是当"鸡头"还是"凤尾"?
查看>>
[茶余饭后]10大毕业生必听得歌曲
查看>>
gdb调试命令的三种调试方式和简单命令介绍
查看>>
C++程序员的几种境界
查看>>
VC++ MFC SQL ADO数据库访问技术使用的基本步骤及方法
查看>>
VUE-Vue.js之$refs,父组件访问、修改子组件中 的数据
查看>>
Vue-子组件改变父级组件的信息
查看>>
Python自动化之pytest常用插件
查看>>
Python自动化之pytest框架使用详解
查看>>
【正则表达式】以个人的理解帮助大家认识正则表达式
查看>>
性能调优之iostat命令详解
查看>>
性能调优之iftop命令详解
查看>>
非关系型数据库(nosql)介绍
查看>>
移动端自动化测试-Windows-Android-Appium环境搭建
查看>>
Xpath使用方法
查看>>