使用舊版代碼時,您無法在一夜之間將其轉換為功能完善的Spring應用程序。 您需要做的是一次添加一點Spring代碼:一步一步地完成,有一種很好的方法。
在以下場景中,您正在處理一些舊代碼,并且編寫了一個名為: MySpringBean的Spring bean,它需要使用舊類: LegacyAppClass
遺留類如下所示:
public class LegacyAppClass {// some old code goes herepublic void legacyDoSomethingMethod() {System.out.println("This is so old it doesn't use a logger....");}
}
…雖然您的新SpringBean如下所示:
public class MySpringBean {private LegacyAppClass injectedBean;@Overridepublic String toString() {return "The toString()";}public LegacyAppClass getInjectedBean() {return injectedBean;}public void setInjectedBean(LegacyAppClass injectedBean) {this.injectedBean = injectedBean;}public void myDoSomethingMethod() {injectedBean.legacyDoSomethingMethod();}}
…如您所見, myDoSomethingMethod ()方法需要調用舊版legacyDoSomethingMethod ()方法。
鑒于任何遺留應用程序都有其創建各種對象的方式,并且您的新Spring代碼將需要使用這些對象來完成其工作,那么您需要一種將遺留對象與閃亮的新對象組合的方式。 這通常涉及將遺留對象添加到您的Spring Context中,并將它們注入到您的對象中,為此,您需要Spring的StaticApplicationContext 。
@Testpublic void loadExternalClassTest2() {LegacyAppClass myInstance = new LegacyAppClass();GenericApplicationContext parentContext = new StaticApplicationContext();parentContext.getBeanFactory().registerSingleton("injectedBean",myInstance);parentContext.refresh(); // seems to be required sometimesApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "SpringIntegrationExample.xml" }, parentContext);MySpringBean mySpringBean = context.getBean(MySpringBean.class);assertNotNull(mySpringBean);mySpringBean.myDoSomethingMethod();System.out.println(mySpringBean.toString());}
在上面的測試代碼中,要注意的第一點是,我創建了一個供測試使用的LegacyAppClass實例,但是在實際應用中,這已經在您的舊代碼庫中的某個位置創建了。 接下來的三行是魔術發生的地方……
GenericApplicationContext parentContext = new StaticApplicationContext();parentContext.getBeanFactory().registerSingleton("injectedBean",myInstance);parentContext.refresh(); // seems to be required sometimes
…在上面的代碼段中,您可以看到我正在創建一個StaticApplicationContext ,然后向其中實用地添加了我的舊類實例。
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "SpringIntegrationExample.xml" }, parentContext);
如上所示,最后的任務是使用適合您的項目的任何方法來創建新的Spring應用程序上下文。 在這種情況下,我使用了眾所周知的ClassPathXmlApplicationContext,但其他類型的應用程序上下文也可以正常工作。
您可能會說這是一個簡單的Micky-Mouse示例,但是從經驗來看,它的擴展性很好。 作為Martin Fowler的Strangler Pattern實現的一部分,目前有兩個完整的舊式JSP Front Strategy MVC應用程序正在使用它(在我于去年10月的博客中詳細介紹了它,名為Everybody Knows About MVC )。
最后,出于完整性考慮,下面是此示例的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-3.0.xsd"><bean id="mySpringBean" class="miscillaneous.springintegration.MySpringBean"><property name="injectedBean" ref="injectedBean"/></bean>
</beans>
參考: JCG合作伙伴 Roger Hughes的 將Spring集成到舊版應用程序中 ? 在Captain Debug的Blog中 。
翻譯自: https://www.javacodegeeks.com/2012/03/integrating-spring-into-legacy.html