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

      

  • 相关阅读:
    oldboy_python_bankSystem practice
    【HCIE-RS复习】- PPP
    【HCIE-RS】PPP详解
    【HCIE-RS】考试说明
    【HCIE-RS】杭州考场(个人考试心得体会)
    DataWorks功能实践速览 05——循环与遍历
    Serverless 工程实践 | 零基础上手 Knative 应用
    前后端、多语言、跨云部署,全链路追踪到底有多难?
    多任务多目标CTR预估技术
    开放搜索查询分析服务架构解读
  • 原文地址:https://www.cnblogs.com/shamgod/p/4586971.html
Copyright © 2020-2023  润新知