[Java] 设计模式之工厂系列 03- spring.properties 的键值读取 / Spring3.0 读取 比较

来源:互联网 发布:水果软件12教程 编辑:程序博客网 时间:2024/05/17 23:04
Moveable
package com.bjsxt.spring.factory;public interface Moveable {void run();}
Car
package com.bjsxt.spring.factory;public class Car implements Moveable {public void run() {System.out.println("冒着烟奔跑中car.......");}}
Train
package com.bjsxt.spring.factory;public class Train implements Moveable {@Overridepublic void run() {System.out.println("小火车呜呜呜");}}
spring.properties    这里用配置文件,所以不需要更改代码,只需要更改, Car - Train 什么的就好!
VehicleType=com.bjsxt.spring.factory.Car
Test
package com.bjsxt.spring.factory;import java.io.IOException;import java.util.Properties;public class Test {/** * @param args * @throws IOException  */public static void main(String[] args) throws Exception {Properties props = new Properties();props.load(Test.class.getClassLoader().getResourceAsStream("com/bjsxt/spring/factory/spring.properties"));String vehicleTypeName = props.getProperty("VehicleType");System.out.println(vehicleTypeName);Object o = Class.forName(vehicleTypeName).newInstance();Moveable m = (Moveable)o;m.run();}}

---------Spring3.0 读取 比较---------------------- 将所需 jar包 加入 build path----

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="v" class="com.bjsxt.spring.factory.Car">    </bean>  <!--  v=com.bjsxt.spring.factory.Car --></beans>
Test
package com.bjsxt.spring.factory;import java.io.IOException;import java.util.Properties;import org.springframework.beans.factory.BeanFactory;import org.springframework.context.support.ClassPathXmlApplicationContext;public class Test {/** * @param args * @throws IOException  */public static void main(String[] args) throws Exception {BeanFactory f = new ClassPathXmlApplicationContext("applicationContext.xml");Object o = f.getBean("v");Moveable m = (Moveable)o;m.run();}}





0 0
原创粉丝点击