model层(业务层+dao层+持久层)
spring开发提倡接口编程,配合di技术可以更好的达到层与层之间的解耦
举例:
现在我们体验一下spring的di配合接口编程,完成一个字母大小写转换的案例
思路如下:
- 创建一个接口ChangeLetter
- 两个类实现接口
- 把对象配置到spring容器中
- 使用
通过上面的案例,我们可以初步体会到di配合接口编程,的确可以减少层(web层)和业务层的耦合度。
思考题:
接口
ValidateUser
有一个方法
check(??)
有两个类实现不同的验证方式
CheckUser1 implements ValidateUser
{
check//到xml验证
}
CheckUser2 implements ValidateUser
{
check();//到数据库验证
}
项目结构:
beans.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" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <!-- <bean id="changeLetter" class="com.litao.inter.UpperLetter"> <property name="str"> <value>abcdef</value> </property> </bean> --> <bean id="changeLetter" class="com.litao.inter.LowwerLetter"> <property name="str" value="ABRTY" /> </bean> </beans>
UpperLetter.java
package com.litao.inter; public class UpperLetter implements ChangeLetter { private String str; @Override public String change() { // TODO Auto-generated method stub //把小写转大写 return str.toUpperCase(); } public String getStr() { return str; } public void setStr(String str) { this.str = str; } }
LowwerLetter.java
package com.litao.inter; //把小写字母变成大写 public class LowwerLetter implements ChangeLetter { public String str; @Override public String change() { // TODO Auto-generated method stub return str.toLowerCase(); } public String getStr() { return str; } public void setStr(String str) { this.str = str; } }
ChangeLetter.java
package com.litao.inter; public interface ChangeLetter { //声明一个方法 public String change(); }
App1.java
package com.litao.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/litao/inter/beans.xml"); //获取,不用接口 //UpperLetter changLetter = (UpperLetter)ac.getBean("changeLetter"); //System.out.println(changLetter.change()); //使用接口来访问bean ChangeLetter changeLetter = (ChangeLetter)ac.getBean("changeLetter"); changeLetter.change(); System.out.println(changeLetter.change()); } }
时间: 2024-12-06 13:53:08