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

      

  • 相关阅读:
    爬虫的基本原理
    爬虫的分类
    gcc编译
    C++字符串总结
    PE文件格式学习笔记
    学习SDR过程中的参考网页
    Linux下源码编译安装遇到的问题
    web | jsp考试复习要点整理
    爬虫 | php封装 | file_get_contents
    re | [NPUCTF2020]EzObfus-Chapter2
  • 原文地址:https://www.cnblogs.com/shamgod/p/4586971.html
Copyright © 2011-2022 走看看