zoukankan      html  css  js  c++  java
  • Java-马士兵设计模式学习笔记-工厂模式-模拟Spring读取Properties文件

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

    二、类

    1.Movable.java

    public interface Movable {
    	void run();
    }
    

      

    2.Car.java

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

      

    3.spring.properties

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

    vechileType=com.tong.spring.factory.Car
    

      

    4.Test.java

    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

    <?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改为如下

    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();
    	}
    }
    

      

  • 相关阅读:
    selenium===介绍
    工具安装===Sublime Text-安装
    Django===django工作流
    python基础=== itertools介绍(转载)
    python基础===如何优雅的写代码(转自网络)
    python基础===一道小学奥数题的解法
    python基础===列表类型的所有方法
    python基础===通过菲波那契数列,理解函数
    python基础===字符串切片
    安全测试===BurpSuite使用教程-附安装包
  • 原文地址:https://www.cnblogs.com/shamgod/p/4586971.html
Copyright © 2011-2022 走看看