IoC and dependency injection · Topic 2 of 7
The IoC container
Definition​
Inversion of control means the Spring container creates your objects (called beans), wires them together and manages them, instead of your code calling new. You describe the beans, and the ApplicationContext builds them and hands them to you.
Example code​
Describe a bean, let the container build it
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
class Greeter {
String greet(String name) { return "Hello, " + name; }
}
@Configuration
class AppConfig {
@Bean
Greeter greeter() { return new Greeter(); } // you describe the bean...
}
class Demo {
public static void main(String[] args) {
try (var context = new AnnotationConfigApplicationContext(AppConfig.class)) { // ...the container builds it
Greeter greeter = context.getBean(Greeter.class);
System.out.println(greeter.greet("Asha"));
System.out.println(context.getBean(Greeter.class) == greeter); // singleton: the same instance
}
}
}
// Output:
// Hello, Asha
// true
Finished this page? Track your progress (saved only in your browser).