spring控制反转,即调用类与被调用类之间的依赖关系由第三方注入。一般调用类A要调用类B,A会主动创建B的实例然后使用实例,现在创建B的实例由spring容器完成并注入给A,A使用就可以了。A由原先的主动去拿B实例变成被动的接受B实例,这中模式就叫控制反转。
1.新建Java Project
2.添加必备的包
spring包下载:spring下载链接
- org.springframework.aop-3.2.9
- org.springframework.aspects-3.2.9
- org.springframework.beans-3.2.9
- org.springframework.context-3.2.9
- org.springframework.context.support-3.2.9
- org.springframework.core-3.2.9
- org.springframework.expression-3.2.9
为了打印信息,我们还需要一个Apache Commons Logging API:commons Logging下载链接
先上代码
(1)定义一个接口
package com.zcl.spring.di;
public interface QuizMaster {
public String popQuestion() ;
}
(2)定义两个类实现popQuestion方法,一个是StrutsQuizMaster类,一个是SpringQuizMaster类
package com.zcl.spring.di;
public class StrutsQuizMaster implements QuizMaster{
@Override
public String popQuestion() {
return "Are you new to Struts?";
}
}
package com.zcl.spring.di;
public class SpringQuizMaster implements QuizMaster{
@Override
public String popQuestion() {
return "Are you new to Spring?";
}
}
(3)新建一个QuizMasterService类,它持有QuizMaster的引用,显示信息给用户
package com.zcl.spring.di;
public class QuizMasterService {
private QuizMaster quizMaster ;
public void setQuizMaster(QuizMaster quizMaster){
this.quizMaster = quizMaster ;
}
public void askQuestion(){
System.out.println(quizMaster.popQuestion()) ;
}
}
(4)
测试类QuizProgram
package com.zcl.spring.di;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class QuizProgram {
public static void main(String args[]){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml") ;
QuizMasterService quizMasterService = (QuizMasterService)context.getBean("quizMasterService") ;
quizMasterService.askQuestion() ;
}
}
(5)
spring配置文件beans.xm
l
<?xml version="1.0" encoding="UTF-8"?>
<beans xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans">
<bean id="springQuizMaster" class="com.zcl.spring.di.SpringQuizMaster"></bean>
<bean id="strutsQuizMaster" class="com.zcl.spring.di.StrutsQuizMaster"></bean>
<bean id="quizMasterService" class="com.zcl.spring.di.QuizMasterService">
<property name="quizMaster">
<ref local="springQuizMaster"/>
</property>
</bean>
</beans>
*以上代码来自http://blog.csdn.net/zclandzzq/article/details/7109860
3. 控制反转实现
在配置文件beans.xml中可以有多个bean,id = "quizMasterService",quizMasterService是类QuizMasterService的实例名,其它的beanID同理解释。
<bean id="quizMasterService" class="com.zcl.spring.di.QuizMasterService">相当于QuizMasterService quizMasterService= new QuizMasterService();
property name = "quizMaster",quizMaster是类QuizMasterService的一个属性名,参见(3);
ref local = "springQuizMaster",springQuizMaster是类SpringQuizMasterd的bean id。
spring容器创建类SpringQuizMaster的实例springQuizMaster,将其(即引用)注入quizMaster,实现控制反转。利用ApplicationContext创建对象获取beans.xml,并利用其getBean()方法获取xml配置文件的bean id。