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:
- What internal operations ocurr during ApplicationContext construction beyond simple object instantiation?
- How does the getBean() method resolve string identifiers to actual object instances?
- 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.