一:DI基本概念
依赖注入(DI),是spring容器实现的基础,在spring-core模块中实现的。所谓DI,就是指对象是被动接受依赖类而不是自己主动去找,换句话说就是指对象不是从容器中查找它依赖的类,而是在容器实例化对象的时候主动将它依赖的类注入给它。
DI作用:
di配合接口编程,的确可以减少层(web层) 和业务层的耦合度.
二:案例-模拟大小写转换
1.编写接口代码
<span style="font-size:18px;">package com.cloud.di;
public interface ChangeLetter {
public String change();
}</span>
2.编写2个接口实现类
LowerLetter.java
<span style="font-size:18px;">package com.cloud.di;
public class LowerLetter implements ChangeLetter{
public String str;
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
@Override
public String change() {
return str.toLowerCase();
}
}</span>
UpperLetter.java<span style="font-size:18px;">package com.cloud.di;
public class UpperLetter implements ChangeLetter{
private String str;
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
@Override
public String change() {
return str.toUpperCase();
}
}</span>
3.编写Spring配置文件
<span style="font-size:18px;"><beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
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-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
<bean id="chanegLetter1" class="com.cloud.di.UpperLetter">
<property name="str" value="abcdef"></property>
</bean>
<bean id="chanegLetter2" class="com.cloud.di.LowerLetter">
<property name="str" value="ABCDEF"></property>
</bean>
</beans></span>
4.编写测试文件
<span style="font-size:18px;">package com.cloud.di;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
/**
* 测试大小写字母的转换
*/
public static void main(String[] args) {
ApplicationContext ac= new ClassPathXmlApplicationContext("applicationContext.xml");
UpperLetter ul = (UpperLetter) ac.getBean("chanegLetter1");
String changeRes1 = ul.change();
System.out.println("小写->大写"+changeRes1);
LowerLetter ll = (LowerLetter) ac.getBean("chanegLetter2");
String changeRes2 = ll.change();
System.out.println("大写->小写"+changeRes2);
}
}</span>