说明:在实际的开发项目中,一般都比较庞大,如果处理不当,会导致对象的依赖关系将一直紧密联系在一起,并且难以修改或者管理。在这一种场景下,sPRing框架的优势便体现出来了—–松耦合。
例子1
说明:运用传统方法输出helloworld语句,主要代码如下
OutputGenerator.java
public interface OutputGenerator { public void output();}OutputGeneratorImpl.java 实现OutputGenerator接口
import com.main.model.OutputGenerator;public class OutputGeneratorImpl implements OutputGenerator{ public void output() { System.out.println("hello world"); }}测试方法
@Test public void testOutputGenerator(){ OutputGeneratorImpl output = new OutputGeneratorImpl(); output.output(); }输出结果为 helloworld 缺点:用这种传统的方式可以实现output方法输出helloworld语句,但是OutputGenerator与OutputGeneratorImpl紧密地联系在一起,假如OutputGenerator类需求有变化,则需要改动代码的地方就会非常多
例子2
依然运用例子1中的OutputGenerator类和OutputGeneratorImpl类,并且再增加一个辅助类,用于输出
OutputGeneratorService
import com.main.impl.OutputGeneratorImpl;import com.main.model.OutputGenerator;public class OutputGeneratorService { OutputGenerator outputGenerator; //default constructor public OutputGeneratorService(){ outputGenerator = new OutputGeneratorImpl(); } public void output(){ outputGenerator.output(); }}测试方法
@Test public void testOutputGeneratorService(){ OutputGeneratorService service = new OutputGeneratorService(); service.output(); }运行结果依然为:hello world 改进:增加一个辅助类来管理类的依赖关系,使得代码的耦合程度不再那么紧密 存在问题:输出的变化依然涉及一部分代码的更改
例子3:运用spring的依赖注入(DI)
修改例子2的OutputGeneratorService
import com.main.impl.OutputGeneratorImpl;import com.main.model.OutputGenerator;public class OutputGeneratorService { OutputGenerator outputGenerator; //default constructor public OutputGeneratorService(){ } public void setOutputGenerator(OutputGenerator outputGenerator){ this.outputGenerator = outputGenerator; } public void output(){ outputGenerator.output(); }}增加一个spring bean的配置文件,并且生命java 对象的依赖关系
<!-- 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"> <bean id="OutputGeneratorService" class="com.main.service.OutputGeneratorService"> <property name="outputGenerator" ref="OutputGeneratorImpl"/> </bean> <bean id="OutputGeneratorImpl" class="com.main.impl.OutputGeneratorImpl"></bean></beans>测试方法
@Test public void testSpringOutput(){ applicationContext context = new ClassPathXmlApplicationContext(new String[] {"beans.xml"}); OutputGeneratorService service =(OutputGeneratorService)context.getBean("OutputGeneratorService"); service.output(); }输出结果依然为hello world 改进之处:现在只需要修改spring的配置文件即可实现不同的输出,而不需要修改代码
新闻热点
疑难解答