IMessage.java
package com.umgsai.spring; public interface IMessage {//定义接口 public abstract String getMessage(); }
Message.java
package com.umgsai.spring; public class Message implements IMessage { public String getMessage() { return "Hello world!"; } }
Hello.java
package com.umgsai.spring; public class Hello implements IMessage{ public String getMessage() { return "你好!"; } }
类路径下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="a1" class="com.umgsai.spring.Message"/> <bean id="a2" class="com.umgsai.spring.Hello"/> </beans>
MainClass.java
MainClass.java package com.umgsai.spring; import org.springframework.beans.factory.BeanFactory; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainClass { public static void main(String[] args) { //IMessage message = MessageFactory.create("1"); //创建spring Bean工厂 BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml"); //BeanFactory factory = new ClassPathXmlApplicationContext("app*.xml");通配符 IMessage message = (IMessage)factory.getBean("a1"); System.out.println(message.getMessage()); message = (IMessage)factory.getBean("a2"); System.out.println(message.getMessage()); } }
运行,控制台输出结果
Hello world!
你好!
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" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <bean id="a1" class="com.umgsai.spring.Message"/> </beans>
本文出自 “阿凡达” 博客,请务必保留此出处http://shamrock.blog.51cto.com/2079212/1253534