spring的DI配合接口编程

Spring开发者提倡接口编程,配合di技术可以解决层与层之间的解耦

举例说明:
现在体验一下spring的di配合接口编程,完成一个字母大小写转换的案例:
思路:
1、创建一个接口ChangeLetter
ChangeLetter.java
package com.inter;
public interface ChangeLetter {
 //声明一个方法
 public String change();
}

2、两个类实现接口

UpperLetter.java

package com.inter;
public class UpperLetter implements ChangeLetter {
    private String str;

    public String getStr() {
        return str;
    }

    public void setStr(String str) {
        this.str = str;
    }

    public String change() {
        //把小写字母->大写
        return str.toUpperCase();
    }
}

LowwerLetter.java

package com.inter;
//把小写字母->大写
public class LowwerLetter implements ChangeLetter {
    private String str;

    public String getStr() {
        return str;
    }
    public void setStr(String str) {
        this.str = str;
    }

    public String change() {
        return str.toLowerCase();
    }
}

3、把对象配置到spring容器中

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.inter.UpperLetter">
        <property name="str">
            <value>aGvGHff</value>
        </property>
    </bean>
    <!--  
    <bean id="changeLetter" class="com.inter.LowwerLetter">
        <property name="str">
            <value>aGvGHff</value>
        </property>
    </bean>    
    -->
</beans>
4、使用
Test.java
package com.inter;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
    public static void main(String[] args) {
        ApplicationContext ac = new ClassPathXmlApplicationContext("com/inter/beans.xml");
        //不使用接口来调用方法
        UpperLetter upperLetter = (UpperLetter) ac.getBean("changeLetter");
        System.out.println(upperLetter.change());
        
        //使用接口来访问bean
        ChangeLetter changeLetter = (ChangeLetter) ac.getBean("changeLetter");
        System.out.println(changeLetter.change());        //beans.xml中配了哪个类,这里的changeLetter就调用哪个类的change()方法
        
    }
}

通过上面的案例,可以初步体会到di配合接口编程,的确可以减少层(web层)与层(业务层)之间的耦合度。

原文地址:https://www.cnblogs.com/jingyunyb/p/3546062.html