CodeGym /Courses /Module 5. Spring /Configuration of Spring applications using XML and Java (...

Configuration of Spring applications using XML and Java (annotations)

Module 5. Spring
Level 1 , Lesson 4
Available

Before writing code, let's figure out why configuration is even needed. A Spring application is like an electrical circuit where each component (or bean) does its job, and configuration defines how to wire those components so everything works. Configuration describes how these components interact with each other and how to tune the app for the project's needs.

There are three main ways to configure Spring:

  1. XML configuration — the old-school way. Good if you enjoy writing piles of XML files.
  2. Annotations — the modern and more convenient approach that cuts down on paperwork.
  3. Java code (Java-based configuration) — a powerful way to customize, giving you flexibility in control.

When should you use each of them?

  • XML is useful for projects where separating configuration from code is a strict requirement.
  • Annotations are great when you want to quickly set up a component without cluttering the project with files.
  • Java code is perfect for complex apps that need dynamic configuration.

Configuration using XML

XML configuration is the oldest but reliable approach. In the past all Spring app settings were stored in .xml files. At first it might seem overly complicated, but it's helpful to understand the basics of how the Spring container works.

Example: Defining a bean in XML

Task: register a bean that represents a simple service.

Let's define the service class:


package com.example.service;

public class GreetingService {
    public void sayHello() {
        System.out.println("Hello from GreetingService!");
    }
}

Create the XML configuration (applicationContext.xml):


<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.xsd">

 <!-- Define bean GreetingService -->
 <bean id="greetingService" class="com.example.service.GreetingService" />

</beans>

Use the bean in code:


package com.example;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.example.service.GreetingService;

public class App {
    public static void main(String[] args) {
        // Load context from XML
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        // Get bean from context
        GreetingService greetingService = context.getBean("greetingService", GreetingService.class);

        // Call bean method
        greetingService.sayHello();
    }
}

This approach shows how the Spring IoC container works: it creates the GreetingService object and manages its lifecycle.


Configuration using annotations

Who doesn't love a bit of magic? With Spring, annotations make life a lot easier. Annotations let you mark classes and their members for automatic configuration.

Main annotations

  • @Component — marks a class to be registered as a bean.
  • @Autowired — injects dependencies into a bean.
  • @ComponentScan — tells where to look for components (beans).

Example: using annotations for configuration

Modify the service class:


package com.example.service;

import org.springframework.stereotype.Component;

@Component // Automatic registration of the class as a bean
public class GreetingService {
    public void sayHello() {
        System.out.println("Hello from GreetingService with annotations!");
    }
}

Set up the main application class:


package com.example;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.example.service.GreetingService;

@Configuration
@ComponentScan(basePackages = "com.example") // Scans the package and looks for components
public class AppConfig {
    @Autowired
    private GreetingService greetingService;

    public void run() {
        greetingService.sayHello();
    }

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

        // Get the AppConfig bean
        AppConfig app = context.getBean(AppConfig.class);
        app.run();

        context.close();
    }
}

The result is the same as with XML, but we got rid of extra files. Pretty magical!


Configuration using Java (the @Configuration annotation)

Java code is a powerful tool in the hands of an experienced developer. Here we create configuration classes and set up beans manually via methods.

Example using @Configuration and @Bean

We want to register a bean but don't want to scan the whole project.

The service class stays the same:


package com.example.service;

public class GreetingService {
    public void sayHello() {
        System.out.println("Hello from GreetingService with Java-based config!");
    }
}

Create the Java configuration:


package com.example.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.example.service.GreetingService;

@Configuration
public class AppConfig {

    @Bean
    public GreetingService greetingService() {
        return new GreetingService(); // Manual creation of the bean
    }
}
Main application class:


package com.example;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.example.service.GreetingService;
import com.example.config.AppConfig;

public class App {
    public static void main(String[] args) {
        // Initialize context with Java configuration
        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

        // Get the bean
        GreetingService greetingService = context.getBean(GreetingService.class);

        // Use the bean
        greetingService.sayHello();
    }
}

Flexibility of Java configuration

You can add complex logic when creating a bean. For example, a bean can depend on configs or external settings:


@Bean
public GreetingService greetingService() {
    if (System.getProperty("user.language").equals("ru")) {
        return new RussianGreetingService();
    }
    return new EnglishGreetingService();
}

Now we see that Java configuration is more geared toward large projects where flexibility is needed.


Comparing approaches: XML, Annotations, Java

Approach Advantages Disadvantages
XML Well-suited for configurations that must be separated from code Lots of boilerplate. You have to write XML even for simple things
Annotations Simplicity, less code for basic tasks All settings are "hidden" in code, which can make maintenance harder
Java Best choice for complex applications, very adaptable Can become complex with a large number of beans

Which approach to choose? If you're a beginner or building a small app, annotations are ideal. For complex systems it's better to use Java configuration, since it's more flexible and easier to customize.

Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION