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

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

  • Spring Boot Pet Clinic App: A Performance Study
  • Improving Backend Performance Part 1/3: Lazy Loading in Vaadin Apps
  • How to Activate New User Accounts by Email
  • Spring Config Integration With a PCF Application: A Step-by-Step Guide

Trending

  • Solid Testing Strategies for Salesforce Releases
  • Is Agile Right for Every Project? When To Use It and When To Avoid It
  • The 4 R’s of Pipeline Reliability: Designing Data Systems That Last
  • AI's Dilemma: When to Retrain and When to Unlearn?
  1. DZone
  2. Coding
  3. Frameworks
  4. Configuring Spring in Stand-Alone Apps

Configuring Spring in Stand-Alone Apps

Here's a quick lesson in bringing Spring Configuration classes and functionality to your own stand-alone apps in the event you need them.

By 
Tomasz J-ski user avatar
Tomasz J-ski
·
Apr. 04, 18 · Tutorial
Likes (18)
Comment
Save
Tweet
Share
45.1K Views

Join the DZone community and get the full member experience.

Join For Free

Spring is a powerful framework — and not only for dependency injection. It can strongly benefit applications as a whole. Sometimes, you need to create your own highly customized stand-alone application instead using an out-of-the-box Spring Boot solution.

Typical cases are custom utility applications used for one-time jobs like email scraping for needed information or custom database migration.

In those cases, you could use Spring Batch, but sometimes, if it is a one-time job, it is easier to just write own code.

You do not need to resign from using Spring in that case — just add it as a stand-alone context and use your favorite Spring features.

Context Loading in Stand-Alone Apps: The Most Critical Feature

AnnotationConfigApplicationContext is the most important class for loading Spring beans in stand-alone applications. It allows annotated classes as inputs, including component package scans and @Configutration-marked classes. In fact, this is the core of every stand-alone Spring application.

Typically, using AnnotationConfigApplicationContext looks like:

public static void main(String[] args) {
                AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
                ctx.register(AppConfig.class);
                ctx.refresh();
}


Where AppConfig.class is a separate @Configuration class with all needed beans.

In less complicated cases application main class could be also configuration, then code look like following

@ComponentScan(basePackages = "YOUR_COMPONENTS_PACKAGE")
@Configuration
public class ApplicationX {

    private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationX .class);
    private SomeService someService;

    @Autowired
    public ApplicationX(SomeService someService) {
        this. someService = someService;
    }

    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(ApplicationX.class);

        ApplicationX appx = context.getBean(ApplicationX .class);
        appx.start();
    }

    private void start() {
        LOGGER.info("ApplicationX started.");
        // do stuff
    }
}


The constructor of the AnnotationConfigApplicationContext class takes multiple arguments of the @Configuration class. That means all configuration could be passed at once during the creation of the context.

That functionality enables adding separate configurations for separate components like databases or custom security features.

Configuration Classes: What They Are

All classes annotated by @Configuration in Spring are considered as configuration classes, but what does this really mean?

According to the Javadoc, the annotation @Configuraion indicates that a class declares one or more @Bean methods and may be processed by the Spring container to generate bean definitions and service requests for those beans at runtime.

So it is like a factory class to produce some beans declared in it.

The simplest example of a @Configuration class looks like the following:

@Configuration
public class ConnectionConfig {

    @Bean
    public MyConnectionService myConnection() {
        // some stuff
    }
}


Summary

Adding a Spring context to a stand-alone application is not difficult, and having it can significantly benefit applications. There is nothing wrong with using your own customized applications for one-time jobs, and Spring has special features to help with dependency injection in stand-alone applications.

By the techniques presented in this article, a developer can add their own Spring beans and inject them where needed — or add whole components like Spring Data to a stand-alone application.

Useful resources

  • https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/Configuration.html
  • https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/AnnotationConfigApplicationContext.html
Spring Framework application app Spring Boot

Opinions expressed by DZone contributors are their own.

Related

  • Spring Boot Pet Clinic App: A Performance Study
  • Improving Backend Performance Part 1/3: Lazy Loading in Vaadin Apps
  • How to Activate New User Accounts by Email
  • Spring Config Integration With a PCF Application: A Step-by-Step Guide

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!