一、spring ioc 简单案例
public interface QuizMaster {
public String popQuestion();
}
我们有两个类继承了上面的接口:
类1SpringQuizMaster:
public class SpringQuizMaster implements QuizMaster {
public String popQuestion() {
return "Are you new to Spring?";
}
}
类2StrutsQuizMaster:
public class StrutsQuizMaster implements QuizMaster {
public String popQuestion() {
return "Are you new to Struts?";
}
}
public class QuizMasterService {
private QuizMaster quizMaster = new StrutsQuizMaster();
public void askQuestion(){
System.out.println(quizMaster.popQuestion());
}
}
public class QuizProgram {
public static void main(String[] args) {
QuizMasterService quizMasterService = new QuizMasterService();
quizMasterService.askQuestion();
}
}
我们可以看到上面的方法很简单,当我们需要打印问题“Are you new to Struts”时,我们需要在QuizMasterService 创建QuizMaster时,QuizMaster quizMaster = new StrutsQuizMaster()。如果我们需要打印问题“Are you new to Spring?”时,需要在在QuizMasterService 创建QuizMaster时,QuizMaster quizMaster = new SpringQuizMaster()。我们可以看到这种代码紧耦合。下面用spring IOC来实现上面的功能。
public class QuizMasterService {
QuizMaster quizMaster;
public void setQuizMaster(QuizMaster quizMaster) {
this.quizMaster = quizMaster;
}
public void askQuestion(){
System.out.println(quizMaster.popQuestion());
}
}我们在QuizMasterService中定义了quizMaster对象并写了一个对此对象的set方法。 我们在使用Spring时可以用构造注入或SET注入,这里我们用了SET注入。下面是Bean的配置文件:
<?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">
<bean id="springQuizMaster" class="com.entity.SpringQuizMaster"></bean>
<bean id="strutsQuizMaster" class="com.entity.StrutsQuizMaster"></bean>
<bean id="quizMasterService" class="com.spring.QuizMasterService">
<property name="quizMaster">
<ref local="strutsQuizMaster"/>
</property>
</bean>
</beans>下面我们调用service方法:
package com.spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class QuizProgram {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("com/resources/beans.xml");
QuizMasterService quizMasterService = (QuizMasterService) context.getBean("quizMasterService");
quizMasterService.askQuestion();
}
}这样如果我们想打印问题“Are you new to Spring?”时,只需在配置文件中修改:
<property name="quizMaster">
<ref local="springQuizMaster"/>
</property>这样我们可以看到代码之间没有那么多的耦合,我们只需在配置文件中对想显示的内容进行修改即可。