一、定义POJO类 package test; /** * IHelloStr接口 * * @author zxs */ public interface IHelloStr { public String getContent(); } package test; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * 基于文件形式,读取HelloWorld所需的字符串。 * * @author zxs */ public class FileHelloStrImpl implements IHelloStr { protected static final Log log = LogFactory.getLog(FileHelloStrImpl.class); private String propfilename; public FileHelloStrImpl(String propfilename) { this.propfilename = propfilename; } public String getContent() { String helloworld = ""; try { Properties properties = new Properties(); //读入输入流 InputStream is = getClass().getClassLoader().getResourceAsStream( propfilename); properties.load(is); is.close(); //获得helloworld键对应的取值 helloworld = properties.getProperty("helloworld"); } catch (FileNotFoundException ex) { log.error(ex); } catch (IOException ex) { log.error(ex); } return helloworld; } } package test; /** * IHelloWorld接口 * * @author zxs * */ public interface IHelloWorld { public abstract String getContent(); } package test; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class HelloWorld implements IHelloWorld { protected static final Log log = LogFactory.getLog(HelloWorld.class); private IHelloStr helloStr; public void setHelloStr(IHelloStr str) { this.helloStr = str; } public String getContent() { return helloStr.getContent(); } } 二、将上述两个POJO配置于类中,构造IoC容器 package test; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.config.java.annotation.Bean; import org.springframework.config.java.annotation.Configuration; import org.springframework.config.java.context.JavaConfigApplicationContext; @Configuration public class JavaConfigDemo { protected static final Log log = LogFactory.getLog(JavaConfigDemo.class); @Bean public IHelloWorld helloWorld(){ HelloWorld hw = new HelloWorld(); hw.setHelloStr(helloStr()); return hw; } @Bean public IHelloStr helloStr(){ return new FileHelloStrImpl("helloworld.properties"); } public static void main(String[] args) { //从注解中装载DI容器配置元数据 JavaConfigApplicationContext context = new JavaConfigApplicationContext(JavaConfigDemo.class); //获得受管Bean IHelloWorld hw = context.getBean(IHelloWorld.class); //返回字符串 log.info(hw.getContent()); } }