Implementing a Basic Spring Application with Hello World Example

Spring's dependency injection mechanism can be demonstrated through a simple Hello World application. Two primary approaches exist for configuring the Spring container: XML-based configuration and annotation-based configuration.

XML Configuration Approach

ApplicationContext container = new ClassPathXmlApplicationContext("application-config.xml");
GreetingService greetingService = (GreetingService) container.getBean("greetingService");
greetingService.displayMessage();

The corresponding XML configuration file:

<context:component-scan base-package="com.example"/>
<bean id="greetingService" class="com.example.service.GreetingService"/>

Annotation-based Configuration Approach

ApplicationContext container = new AnnotationConfigApplicationContext(AppConfig.class);
GreetingService greetingService = (GreetingService) container.getBean("greetingService");
greetingService.displayMessage();

The Java configuration class:

@ComponentScan("com.example")
public class AppConfig {
    @Bean
    public GreetingService greetingService() {
        return new GreetingService();
    }
}

This initialization process raises several technical questions:

  1. What internal operations ocurr during ApplicationContext construction beyond simple object instantiation?
  2. How does the getBean() method resolve string identifiers to actual object instances?
  3. What distinguishes Spring-managed beans from manually instantiated objects?

Modern Spring applications typically use specialized ApplicationContext implementations:

  • Spring MVC utilizes XmlWebApplicationContext for web applications
  • Spring Boot defaults to AnnotationConfigApplicationContext for ennotation-driven configuration

The core principles demonstrated in this basic example form the foundasion for more advanced Spring features including dependency injection, aspect-oriented programming, and transaction management.

Tags: Spring Framework Dependency Injection IoC Container Java Configuration XML Configuration

Posted on Wed, 28 Oct 2026 16:26:08 +0000 by vidago