一 简介
spring开发提倡接口编程,配合di技术可以层与层的解耦。
二 项目
现在我们体验一下spring的di配合接口编程的,完成一个字母大小写转换的案例。
三 步骤
1 创建一个接口ChangeLetter
package com.hsp.inter;
public interface ChangeLetter {
//声明一个方法
public String change();
}
2 两个类实现接口
LowwerLetter
package com.hsp.inter;
//把小写字母-》大写
public class LowwerLetter implements ChangeLetter {
private String str;
public String change() {
// TODO Auto-generated method stub
return str.toLowerCase();
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
}
UpperLetter
package com.hsp.inter;
public class UpperLetter implements ChangeLetter {
private String str;
public String change() {
//把小写字母->大写
return str.toUpperCase();
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
}
3 把对象配置到spring容器中
<?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:context="http://www.springframework.org/schema/context";
xmlns:tx="http://www.springframework.org/schema/tx";
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-2.5.xsd";>
<!--
<bean id="changeLette" class="com.hsp.inter.UpperLetter">
<property name="str">
<value>abcef</value>
</property>
</bean>-->
<bean id="changeLette" class="com.hsp.inter.LowwerLetter">
<property name="str" value="ABRTY" />
</bean>
</beans>
4 测试代码
package com.hsp.inter;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App1 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext ac=new ClassPathXmlApplicationContext("com/hsp/inter/beans.xml");
//获取,不用接口
//UpperLetter changeLetter=(UpperLetter) ac.getBean("changeLette");
//System.out.println(changeLetter.change());
//使用接口来访问bean
ChangeLetter changeLetter=(ChangeLetter) ac.getBean("changeLette");
System.out.println(changeLetter.change());
}
}
5 测试结果
abrty
6 小结
通过上面的案例,我们可以初步体会到di配合接口编程,的确可以减少层耦合度。