Spring学习一之IOC工作原理 2

来源:互联网 发布:ubuntu提升超级权限 编辑:程序博客网 时间:2024/06/06 02:48

上一篇简单介绍了依赖,这一篇把第一篇的内容重构。

重构代码:

创建HelloStr接口:

/** *  */package com.nantian.spring.example2;/** * @author ps * */public interface HelloStr {public String getContent();}


其次声明FileHelloStr类,实现HelloStr接口:

/** *  */package com.nantian.spring.example2;import java.io.InputStream;import java.util.Properties;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;/** * @author ps * */public class FileHelloStr implements HelloStr {protected static final Log log = LogFactory.getLog(FileHelloStr.class);private String profilename;public FileHelloStr(String profilename) {this.profilename = profilename;}/* (non-Javadoc) * @see com.nantian.spring.example2.HelloStr#getContent() */@Overridepublic String getContent() {String helloWorld = "";try{Properties properties = new Properties();InputStream is = getClass().getClassLoader().getResourceAsStream(profilename);properties.load(is);is.close();helloWorld = properties.getProperty("helloworld");}catch (Exception e) {log.error(e.getMessage());}return helloWorld;}}


重构HelloWorld类:

/** *  */package com.nantian.spring.example2;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;/** * @author ps * */public class HelloWorld {protected static final Log log = LogFactory.getLog(HelloWorld.class);private HelloStr helloStr;public HelloWorld(HelloStr helloStr) {this.helloStr = helloStr;}public String getContent(){return helloStr.getContent();}}


还要重构HelloWorldClient类:

/** *  */package com.nantian.spring.example2;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;/** * @author ps * */public class HelloWorldClient {protected static final Log log = LogFactory.getLog(HelloWorldClient.class);/** * @param args */public static void main(String[] args) {FileHelloStr fileHelloStr = new FileHelloStr("helloworld.properties");HelloWorld helloWorld = new HelloWorld(fileHelloStr);log.info(helloWorld.getContent());}}


 

运行其输出结果跟上一篇一样。