|
spring IOC基础 现在基于配置文件的框架是主流的,不管是各式各样的开源spring、webwork、hibernate全是如此.spring同样也是基于配置文件的。配置文件的好处显而易见,在基于接口编程的过程中,如果子类在不符合需求的时候,只需要改变配置文件,而不需要改变类文件。不过现在越来越多的开源全是这样的配置,真让我有点担心是不是有些过于麻烦了。至少这么多的配置,其实弄的我也是头大的。 spring框架的整体核心思想就是基于IOC设计实现的.所谓IOC,直译过来就是控制反转,还有人称为依赖注入.不多说,先看一个小例子: 在论坛的设计过程中,论坛中的贴子都是从数据库中读取的,也有一些贴子来源的网络或者文件,代码如下: 业务层的接口如下: public interface Service { ForumThread getThread(int threadID); String getCategory(); } 数据库业务实现如下: public class DBService implements Service { public String getCategory() { return "DB"; } public ForumThread getThread(int threadID) { return null; } } 文件的业务实现如下: public class FileService implements Service { public String getCategory() { return "File"; } public ForumThread getThread(int threadID) { return null; } } 通常情况下,我们的都是在数据库中查找所有的贴子,客户端代码如下: public class Client { private Service service; public Client(Service service) { this.service = service; } public Service getService() { return service; } public void setService(Service service) { this.service = service; } public static void main(String[] args) { Client client = new Client(new DBService()); System.out.println(client.getService().getCategory()); } } 这样我们实现了一个基本的数据库读取的service。这样虽然同样实现了功能,但是这里有一个很不好的地方,就是在客户端已经把代码直接写到客户端处,在这里就是Client中。但是如果现在有这样的一种需求,现在要是文件中读取代码,这样我们得被迫去修改Client的代码,这样如果代码量很大的情况下,我们会把这样的时间浪费太多了。下面采用基于IOC的代码: Client如下: public class Client2 { private Service service; public Service getService() { return service; } public void setService(Service service) { this.service = service; } public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("com/websidesoft/core/applicationContext.xml"); Client2 client = (Client2)ctx.getBean("client2"); System.out.println(client.getService().getCategory()); } } 对应的applicationContext.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" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <bean id="dbService" class="com.websidesoft.core.DBService"/> <bean id="fileService" class="com.websidesoft.core.FileService"/> <bean id="client2" class="com.websidesoft.core.Client2"> <property name="service"> <ref local="dbService"/> </property> </bean> </beans> 我们看到,如果需要改变贴子的来源,是不需要改动任何的代码的,只需要把xml文中的<ref local="dbService"/>这一句改成<ref local="fileService"/>便可实现我们想要的功能. 上面的代码就是以IOC形式注入的,我们看到,没有任何的new语立在客户端的代码中。除此之外,spring还支持构造函数注入。 上面就是一个最简单的spring IOC应用.有兴趣的人可以研究一下spring的初使化过程.
|