Spring Framework從誕生之日起,受到了越來越多的關注。最近,新的開源項目大多支持Spring Framework。國內目前也有專門的網站(http://spring.jactiongroup.net/)。那它為什么如此受歡迎呢?
我想最重要的是,EJB讓每個人都痛恨。要編寫一個EJB,需要寫LocalHome, RemoteHome, Bean,
LocalInterface,
RemoteInterface,需要一個標準描述符,一個特殊廠商描述符(Weblogic、WebSphere都不一樣),如果是Entity
Bean,還需要Mapping文件。如此之多,實在麻煩。但EJB最重要的是解決Transaction問題,沒有Spring之前,沒有其他方法能夠
描述式的解決它。每個人、每個公司為了解決Transaction的問題,編程的寫法都不一樣,百花齊放。于是,在最需要它的時候,Spring出現了。
Spring的功能非常多。但對于一個產品,最重要的是如何用好它的精華。Spring包含AOP、ORM、DAO、Context、Web、
MVC幾個部分組成。Web、MVC暫不用考慮,用成熟的Struts、JSP或Webwork更好。DAO由于目前Hibernate、JDO的流行,
也可不考慮。因此最需要用的是AOP、ORM、Context。
Context中,最重要的是Beanfactory,它是將接口與實現分開,非常重要。以前我們寫程序,如一個接口IDocument,一個實現
類Document1。在寫程序時,需寫成IDocument doc = new
Document1(),一旦我們的實現類需改變時,變為Document2,則程序需寫成IDocument doc = new
Document2(),所有用到的地方全需改。Beanfactory幫我們解決了這個問題,用context后,寫法變為IDocument
doc=(IDocument)beanFactory.getBean("doc")。如果實現類從Document1改為Document2,直接在
配置文件改就可以了。Context是Bean
factory的進一步抽象。很多人都喜歡用ApplicationConext,用Servlet把它Load。這樣就把Bean
Factory與Web綁定在一起。如果是Fat Client或Remote調用,則這些Bean
factory就很難調用,實際是將表現層與業務層綁定的太緊。推薦的方法是SingletonBeanFactoryLocator。具體為:
BeanFactoryLocator bfLocator = SingletonBeanFactoryLocator.getInstance();
BeanFactoryReference bf = bfLocator.useBeanFactory("beanFactory");
// now use some bean from factory
return bf.getFactory().getBean(name);
<beans>
<bean id="beanFactory" class="org.springframework.context.support.ClassPathXmlApplicationContext">
<constructor-arg>
<list>
<value>dataAccessContext.xml</value>
<value>securityContext.xml</value>
<value>
</value>
</list>
</constructor-arg>
</bean>
</beans>
這樣,就可隨時動態擴展,實現組件式的開發。
(未完,待續)
posted on 2008-08-14 15:13
前方的路 閱讀(297)
評論(0) 編輯 收藏 所屬分類:
Java技術