Beans, dependency injection, and the ApplicationContext — the one idea the whole framework is built on.
Without a framework, objects create their own collaborators:
class TransferService {
// tightly coupled: TransferService decides the exact implementation
private AccountRepository repo = new JdbcAccountRepository();
}
Now TransferService can never use a different repository, and you can't unit-test it with a
fake. It controls its own dependencies. Inversion of Control (IoC) flips that: the
framework decides what to create and hands dependencies in.
class TransferService {
private final AccountRepository repo;
// the dependency is injected from outside — constructor injection
TransferService(AccountRepository repo) { this.repo = repo; }
}
A bean is simply an object that the Spring IoC container instantiates,
assembles, and manages. You describe what beans exist and how they depend on each other (via annotations,
Java @Configuration, or XML); the container reads that metadata and builds the fully-wired
object graph for you.
| Term | What it is |
|---|---|
| Bean | An object created & managed by the container. If Spring made it, it's a bean. |
| Container | The thing that reads config metadata and produces the wired beans. |
| Configuration metadata | How you tell the container what to build: annotations, @Bean methods, or XML. |
There are two container interfaces. You will use ApplicationContext — but the exam tests
that you know how they differ.
BeanFactory | ApplicationContext | |
|---|---|---|
| Role | Most basic container | Superset — extends BeanFactory |
| Singleton creation | Lazy (on first request) | Eager at startup |
| Extras | Just DI | Events, i18n (MessageSource), resource loading, auto-registers post-processors |
ApplicationContext eagerly pre-instantiates singleton beans when the context starts,
so misconfiguration blows up immediately at startup — not later at first use. A plain BeanFactory
is lazy. This "eager vs lazy" line is a classic question.
// From @Configuration / @Component classes (the modern default)
ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
// From XML on the classpath
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
TransferService svc = ctx.getBean(TransferService.class);
Note: DefaultListableBeanFactory is a BeanFactory, not an
ApplicationContext — a favourite distractor in "which of these is an ApplicationContext?" questions.
final fields, guarantees fully-built objects, trivially testable. Mandatory dependencies.@Autowired on a field. Discouraged: hides dependencies, can't be final, hard to instantiate in a plain unit test.@Autowired on it — Spring uses it automatically.
Sections 1.1–1.4. Read the intro, "Container Overview", and "Dependencies". 20 minutes, and it maps 1-to-1 onto this lesson.
Exam-shaped questions. Answer before revealing — retrieval is what makes it stick.