1 声明接口类
package com.gc.inter; public interface Hello { /** * Add By ZJY * * @return 输出问侯语 2016年2月17日 */ public String doSalutation(); }
2 声明实体类
package com.gc.action; import com.gc.inter.Hello; public class ChHello implements Hello { public String msg = null; public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } /* * 实现接口方法 */ public String doSalutation() { return "你好" + this.msg; } }
package com.gc.action; import com.gc.inter.Hello; public class EnHello implements Hello { public String msg = null; public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } /* * 实现接口方法 */ public String doSalutation() { return "hello" + this.msg; } }
3 调用
package com.gc.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; import com.gc.action.HelloWorld; import com.gc.inter.Hello; public class TestHelloWorld { public static void main(String[] args) { @SuppressWarnings("resource") ApplicationContext actx = new FileSystemXmlApplicationContext("config.xml"); Hello hello=(Hello)actx.getBean("HelloWorld"); System.out.println(hello.doSalutation()); } }
4 xml配置
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <!-- 定义一个bean id表示唯一一个bean class表示bean的来源 --> <bean id="HelloWorld" class="com.gc.action.EnHello"> <!-- 将其变量msg通过依赖注入 --> <property name="msg"> <value>ch</value> </property> </bean> </beans>
实现spring的IoC(反向控制 )
时间: 2024-10-13 22:01:58