Return to site

[Spring Cert Lesson]🪴⚙️ SPRING APPLICATIONCONTEXT — AND 3 BEAN LOADING WAYS

· spring,java,book

🔸 TL;DR

The ApplicationContext is Spring’s container. It creates and wires beans, manages scopes & lifecycle, publishes events, and resolves messages. Prefer typed lookups; use names/@Qualifier when multiple beans share a type. ✅

Section image

🔸 WHAT IT DOES

▪️ Bean creation & DI (wiring)

▪️ Scopes & lifecycle callbacks (@PostConstruct, @PreDestroy)

▪️ Events (ApplicationEventPublisher)

▪️ Message resolution (i18n)

▪️ Environment & property management 🌱

🔸 MINIMAL BOOTSTRAP (PLAIN SPRING — EXAM-FRIENDLY)

// Create the context from Java config
try (AnnotationConfigApplicationContext ctx =
 new AnnotationConfigApplicationContext(ApplicationConfig.class)) {
 // Typed lookup (recommended)
 TransferService service = ctx.getBean(TransferService.class);
 service.transfer(new MonetaryAmount("300.00"), "1", "2");
}

🔸 WITH SPRING BOOT (CONVENIENT, NOT REQUIRED)

ApplicationContext ctx = SpringApplication.run(ApplicationConfig.class);
TransferService service = ctx.getBean(TransferService.class);

🔸 PROGRAMMATIC LOOKUPS — 3 WAYS

ApplicationContext ctx =
 new AnnotationConfigApplicationContext(ApplicationConfig.class);
// 1) By id (unsafe): requires cast
TransferService ts1 = (TransferService) ctx.getBean("transferService");
// 2) By id + type (safer)
TransferService ts2 = ctx.getBean("transferService", TransferService.class);
// 3) By type only (best when unique)
TransferService ts3 = ctx.getBean(TransferService.class);

🔸 TAKEAWAYS

▪️ Prefer typed lookups for compile-time safety.

▪️ If multiple beans share a type, qualify by name or @Qualifier.

▪️ Use plain Spring bootstrapping for fundamentals (and certification prep).

▪️ Boot is great for app startup ergonomics; the container concepts are the same.

▪️ Close contexts you create (e.g., try-with-resources) to trigger lifecycle hooks. 🔁

#Spring #SpringBoot #Java #DependencyInjection #IoC #Bean #SoftwareEngineering #CleanCode #SpringProfessional #Certification

🍃📗 Grab your Spring cert Book: https://spring-book.mystrikingly.com