DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • A Practical Guide to Creating a Spring Modulith Project
  • Spring Application Listeners
  • Creating Application using Spring Roo and Deploying on Google App Engine
  • Enterprise RIA With Spring 3, Flex 4 and GraniteDS

Trending

  • Memory Leak Due to Time-Taking finalize() Method
  • Docker Base Images Demystified: A Practical Guide
  • A Simple, Convenience Package for the Azure Cosmos DB Go SDK
  • Designing a Java Connector for Software Integrations
  1. DZone
  2. Coding
  3. Frameworks
  4. Integrating Spring Into Legacy Applications

Integrating Spring Into Legacy Applications

By 
Roger Hughes user avatar
Roger Hughes
·
Mar. 17, 12 · Interview
Likes (0)
Comment
Save
Tweet
Share
13.4K Views

Join the DZone community and get the full member experience.

Join For Free
One of the things that all Spring developers like to do is to shoehorn Spring into any application they work on - it’s one of my guilty pleasures in life: you see some code, think it’s rubbish because it contains several well known anti-patterns and then think how cool it would be if this app was a Spring app.

When working with legacy code, you can’t convert it into a fully fledged Spring app over night, that takes time. What you need to do is to add Spring code a little at a time: piece by piece and there’s one good way of doing that.

In the following scenario, you’re working on some legacy code and you’ve written a Spring bean called: MySpringBean and it needs to use the legacy class: LegacyAppClass

The legacy class looks like this:
public class LegacyAppClass {
  // some old code goes here

  public void legacyDoSomethingMethod() {
    System.out.println("This is so old it doesn't use a logger....");
  }
}
...whilst your new SpringBean looks like this:
public class MySpringBean {

  private LegacyAppClass injectedBean;

  @Override
  public String toString() {
    return "The toString()";
  }

  public LegacyAppClass getInjectedBean() {
    return injectedBean;
  }

  public void setInjectedBean(LegacyAppClass injectedBean) {
    this.injectedBean = injectedBean;
  }

  public void myDoSomethingMethod() {
    injectedBean.legacyDoSomethingMethod();
  }

}
...as you can see, the myDoSomethingMethod() method needs to call the legacy legacyDoSomethingMethod() method.

Given that any legacy application will have its own way of creating various objects, and that your new Spring code will need to use those objects to get its job done, then you need a way of combining the legacy objects with your shiny new ones. This will usually involve adding the legacy objects into your Spring Context and injecting them into your objects and to do this you need Spring’s StaticApplicationContext.

 
@Test
  public void loadExternalClassTest2() {

    LegacyAppClass myInstance = new LegacyAppClass();
    GenericApplicationContext parentContext = new StaticApplicationContext();

    parentContext.getBeanFactory().registerSingleton("injectedBean",
        myInstance);
    parentContext.refresh(); // seems to be required sometimes

    ApplicationContext context = new ClassPathXmlApplicationContext(
        new String[] { "SpringIntegrationExample.xml" }, parentContext);

    MySpringBean mySpringBean = context.getBean(MySpringBean.class);
    assertNotNull(mySpringBean);

    mySpringBean.myDoSomethingMethod();

    System.out.println(mySpringBean.toString());
  }


In the test code above the first point to note is that I create an instance of LegacyAppClass for use by the test, but in a real world app this will have already been created somewhere in your legacy code base. The next three lines is where the magic happens...
   
GenericApplicationContext parentContext = new StaticApplicationContext();

    parentContext.getBeanFactory().registerSingleton("injectedBean",
        myInstance);
    parentContext.refresh(); // seems to be required sometimes

...in the snippet above, you can see that I’m creating a StaticApplicationContext and then pragmatically adding my legacy class instance to it.
    ApplicationContext context = new ClassPathXmlApplicationContext(
        new String[] { "SpringIntegrationExample.xml" }, parentContext);

The final task, as shown above, is to then create a new Spring application context using whatever method is suitable for your project. In this case, I’ve used the proverbial ClassPathXmlApplicationContext but other types of app context work just as well.

You may say that this is a simple Micky-Mouse example, but from experience it does scale very well. It’s currently being used by a couple of full scale old style JSP Front Strategy MVC applications, (covered in detail in my blog from last October called Everybody Knows About MVC), as part of an implementation of Martin Fowler’s Strangler Pattern.

Finally, in the interests of completeness, below is the XML config for this example:

<?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>
Spring Framework application

Published at DZone with permission of Roger Hughes, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • A Practical Guide to Creating a Spring Modulith Project
  • Spring Application Listeners
  • Creating Application using Spring Roo and Deploying on Google App Engine
  • Enterprise RIA With Spring 3, Flex 4 and GraniteDS

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: