总结上一节课内容
spring实际上是一个容器框架,可以配置各种bean,并且可以维护bean与bean的关系,当需要某个bean时,可以用getbean(id)获取bean
spring核心引用包
spring的核心文件applicationContext.xml,此文件可以取其它名称
配置bean,通过id,及class文件属性进行创建
*使用ApplicationContext ac = new
ClassPathXmlApplicationContext(“applicationContext.xml”);加载容器*IOC: inverse of controll :控制反转,把创建对象(bean)和维护对象(bean)的权利,从程序中转移到spring的容器中(applicationContext.xml)
Di:dependency injection依赖注入:是spring的核心技术
sping开发提倡接口编程,配合di接口编程,减少层与层之间耦合度
案例:字母的大小写转换
- 创建一个接口ChangeLetter
- 用两个类实现此接口
- 把对象配置到spring容器中
- 使用
接口ChangeLetter
package com.study.inter
public interface ChangeLetter{
public String change();
}
实现类UpperLetter,小写变大写
package com.service;
/**
* Created by hejian on 16/9/7.
*/
public class UpperLetter implements ChangeLetter{
private String str;
public String Change(){
//把小写转成大写
str.toUpperCase();
System.out.println(getStr());
return str.toUpperCase();
}
public String getStr(){
return str.toUpperCase();
}
public void setStr(String str){
this.str = str;
}
}
实现类LowerLetter,大写转小写
package com.service;
/**
* Created by hejian on 16/9/7.
*/
public class LowerLetter implements ChangeLetter {
private String str;
public String Change(){
//大写 -> 小写
System.out.println(str.toLowerCase());
return str.toLowerCase();
}
public void setStr(String str){
this.str = str;
}
public String getStr(){
return str;
}
}
xml配置文件如下,可以创建一个 beans.xml文件放在对应包的下面,如:com.service下创建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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- id是不能相同的,为了演示解偶,故写成一致,注释掉,切换时在打开注释掉另一个,这样可以通bean来选择对应的逻辑操作-->
<bean id ="changeLette" class="com.service.LowerLetter">
<property name="str" value="ABCED" />
</bean>
<!--<bean id ="changeLette" class="com.service.UpperLetter">-->
<!--<property name="str" value="abcd" />-->
<!--</bean>-->
</beans>
创建测试类
package com.service;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Created by hejian on 16/9/8.
*/
public class TestSpring {
public static void main(String[ ] args){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("com/service/beans.xml");
LowerLetter changeLetter = (LowerLetter) applicationContext.getBean("changeLette");
changeLetter.Change();
//使用接口来访问bean,接口可以转,此处可以解偶操作,通过切换beans.xml文件中bean进行切换changeLette,而无需更改相应类中的代码就能实现切换
ChangeLetter changeLetter1 = (ChangeLetter) applicationContext.getBean("changeLette");
changeLetter1.Change();
}
}
通过上述案例,可以了解到di配合接口编程带来的方便,可以减少程序之间的耦合度