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
Please enter at least three characters to search
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

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

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

Related

  • A Practical Guide to Creating a Spring Modulith Project
  • Distributed Tracing System (Spring Cloud Sleuth + OpenZipkin)
  • Java, Spring Boot, and MongoDB: Performance Analysis and Improvements
  • Spring Boot Secured By Let's Encrypt

Trending

  • Manual Sharding in PostgreSQL: A Step-by-Step Implementation Guide
  • Ethical AI in Agile
  • A Complete Guide to Modern AI Developer Tools
  • 5 Subtle Indicators Your Development Environment Is Under Siege
  1. DZone
  2. Coding
  3. Frameworks
  4. Migrating a Legacy Spring Application to Spring Boot 2

Migrating a Legacy Spring Application to Spring Boot 2

Out with the old, in with Spring Boot 2.

By 
Marios Karagiannopoulos user avatar
Marios Karagiannopoulos
DZone Core CORE ·
Updated Sep. 16, 19 · Tutorial
Likes (12)
Comment
Save
Tweet
Share
69.0K Views

Join the DZone community and get the full member experience.

Join For Free

Legacy code

Out with the old, in with Spring Boot 2

Recently, we decided to monitor the metrics of legacy Spring applications we were running on our production systems. While searching around, I realized that a nice way to not reinvent the wheel was to integrate my app with the Spring Boot Actuator. By using the actuator, we have many tools like Grafana and Prometheus for easily monitoring our applications. However, in order to integrate such a legacy Spring application with the Spring Boot Actuator, you need to make it Spring-Boot-ready first.

Since Spring Boot 1.5 reached the end of its life at the beginning of August, I decided to move to Spring Boot 2 and start playing with it.

pom.xml

First of all, we should add Spring Boot 2 starters as the parent project in our pom.xml:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.7.RELEASE</version>
    <relativePath/>
</parent>


By adding the above parent project, we can then access all of the Spring Boot 2.1.7 dependencies. So if you get compilation errors regarding your dependency code, you may keep the old versions of your dependencies by keeping the <version> tag in the relevant dependency. On the other hand, if you remove the version tag, you will get Spring Boot's dependencies versions.

Here are the extra Spring Boot dependencies I used:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
        </dependency>


Main Application Source

Regarding the main application source, here is my old and new code:

Old App.java

package com.company.app;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.company.app.Constants;

public final class App {

    private static final Logger LOGGER = LoggerFactory.getLogger(App.class);

    private App() {
    }

    public static void main(String[] args) {
        try {
            SpringApplicationLauncher.launch(Constants.CONTEXT_XML);
        } catch (Exception exception) {
            LOGGER.error("[App] could not launch app.", exception);
        }
    }

}


New App.java

package com.company.app;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.actuate.autoconfigure.endpoint.EndpointAutoConfiguration;
import org.springframework.boot.actuate.autoconfigure.health.HealthIndicatorAutoConfiguration;
import org.springframework.boot.actuate.autoconfigure.metrics.MetricsAutoConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
import org.springframework.boot.autoconfigure.jms.JndiConnectionFactoryAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.boot.autoconfigure.security.servlet.SecurityFilterAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportResource;
import com.company.app.Constants;

@SpringBootApplication
@ImportResource({ "classpath*:" + Constants.CONTEXT_XML })
@Import({ EndpointAutoConfiguration.class, HealthIndicatorAutoConfiguration.class, MetricsAutoConfiguration.class, SecurityProperties.class })
@EnableAutoConfiguration(exclude = { JndiConnectionFactoryAutoConfiguration.class, DataSourceAutoConfiguration.class,
        HibernateJpaAutoConfiguration.class, JpaRepositoriesAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class,
        SecurityAutoConfiguration.class, SecurityFilterAutoConfiguration.class })
public class App {

    private static final Logger LOGGER = LoggerFactory.getLogger(App.class);

    public static void main(String[] args) {
        try {
            SpringApplication springApplication = new SpringApplicationBuilder().sources(App.class).web(WebApplicationType.NONE).build();
            springApplication.run(args);
        } catch (Exception exception) {
            LOGGER.error("[App] could not launch app.", exception);
        }
    }

}


As you can see, the @SpringBootApplication annotation is now used and brings all the auto Spring annotations in our application. However, due to several compilation errors I experienced, I disabled some of them, as you can see in exclude option of @EnableAutoConfiguration.

HealthCheck Logic

We should implement the health check logic in a separate class by implementing the HealthIndicator interface.

package com.company.app;

import javax.inject.Inject;
import javax.inject.Named;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;

import com.company.app.BrokerConnection;
import com.company.app.Provider;

@Component
public class AppHealthCheck implements HealthIndicator {

    private final Logger logger = LoggerFactory.getLogger(AppHealthCheck.class);

    @Inject
    @Named("brokerConnectionProvider")
    private Provider<BrokerConnection> brokerConnectionProvider;

    @Override
    public Health health() {
        BrokerConnection connection = check();
        if (connection != null) {
            return Health.down().withDetail("Broker Connection is not running ", connection.getName()).build();
        }
        return Health.up().build();
    }

    private BrokerConnection check() {
        for (BrokerConnection connection : brokerConnectionProvider.getAll()) {
            logger.info("Health Checking: broker connection {}.", connection);
            if (!connection.isRunning()) {
                return connection;
            }
        }
        return null;
    }
}


The above code is executed each time a new JMX call is executed the managed Bean: org.springframework.boot.Endpoint.Health.health(). 

Image title

Example Result:

status=UP
details={appHealthCheck={status=UP}, mail={status=UP, details={location=mailserver.domain.local:25}}, diskSpace={status=UP, details={total=124578889728, free=70527569920, threshold=10485760}}, jms={status=UP, details={provider=ActiveMQ}}}


CommandLineRunner

The previous code implemented a custom interface in a separate class in order to hold the run() and shutdown() methods for the application launch. Now, we use the CommandLineRunner  functional interface, which implements run(String... args) method instead. Of course, I didn't change the content of this method at all.

Spring Framework Integration Header Interface

My old app was based on Spring Framework 4.xx while Spring Boot 2 uses Spring Framework 5.xx. Therefore, there were complaints of this abstract interfaceimport org.springframework.integration.annotation.Header;

Since it is deprecated in Spring 5, the solution was as simple as to just replace it with import org.springframework.messaging.handler.annotation.Header;

spring.main.allow-bean-definition-overriding=true

If you use Spring XML configurations to define your beans and you have duplicate bean definitions in the code and the XML files you may experience some runtime errors. The above Spring boot java property can be used in your properties configuration file to ignore such cases and your app will continue work as expected.

Maven Placeholders

In our apps, we use in logback.xml configurations Maven references like ${project.version}. Such references should change to @project.version@ in order for Maven resource filtering to resolve during build time and eventually replace them. Same thing can be done in scripts .bat or .sh files with other variables as well (e.g. @project.build.finalName@ ).

Logback

Logback configuration is enabled by using the JVM argument  -Dlogging.config=./logback.xml instead of -Dlogback.configurationFile=./logback.xml, which we used in the old application.

Happy migrating!

Further Reading

Spring Boot 2 Applications and OAuth2 - Legacy Approach

Spring Framework Spring Boot application

Opinions expressed by DZone contributors are their own.

Related

  • A Practical Guide to Creating a Spring Modulith Project
  • Distributed Tracing System (Spring Cloud Sleuth + OpenZipkin)
  • Java, Spring Boot, and MongoDB: Performance Analysis and Improvements
  • Spring Boot Secured By Let's Encrypt

Partner Resources

×

Comments
Oops! Something Went Wrong

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:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!