Beans and the application context
40 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)In the Why Spring module, main built every object with new and passed it along by hand. As ShopLite grows, that wiring becomes the hardest part. Spring can create and connect the objects for you.
Beans: objects Spring creates and manages
A bean is an object that Spring creates, connects to other objects and keeps for the whole life of the app. Marking a class with @Component makes Spring create one bean from it at startup.
Mark a class with @Component and start the app. Spring finds the class, calls its constructor once and keeps the object. No line below calls new PriceFormatter().
Example 1 · PriceFormatter.java, DiLabApplication.java
Runs in: the di-lab practice project (Spring Boot 4.1)
package com.shoplite.lab;
import java.math.BigDecimal;import java.math.RoundingMode;
import org.springframework.stereotype.Component;
@Componentpublic class PriceFormatter {
public PriceFormatter() { System.out.println("PriceFormatter created by Spring"); }
public String format(BigDecimal amount) { return "Rs " + amount.setScale(2, RoundingMode.HALF_UP).toPlainString(); }}
package com.shoplite.lab;
import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplicationpublic class DiLabApplication {
public static void main(String[] args) { SpringApplication.run(DiLabApplication.class, args); }}PriceFormatter created by Spring
What this code does
@ComponentmarksPriceFormatteras a bean. No line in the code callsnew PriceFormatter(), yet the constructor ran: Spring created the object insideSpringApplication.run.@SpringBootApplicationon the main class makes Spring look for@Componentclasses incom.shoplite.laband its sub-packages. The How Spring Boot Works module explains this search (component scanning).- The
printlnin the constructor only shows when Spring creates the bean. Real beans do not print.
The examples in this module run in a small practice project, di-lab. Create it on start.spring.io like shoplite-api, but with no dependencies, artifact di-lab and package name com.shoplite.lab. Add spring.main.banner-mode=off and logging.level.root=warn to its application.properties, so the console shows only what your code prints.
The application context: getBean and bean names
The application context is the container that holds every bean of a Spring app. SpringApplication.run builds it and returns it as a ConfigurableApplicationContext, and getBean asks it for a bean.
SpringApplication.run returns the context. Ask it for a bean by type with getBean(PriceFormatter.class), by name with getBean("priceFormatter", PriceFormatter.class), and list the bean names.
Example 2 · DiLabApplication.java, PriceFormatter.java
Runs in: the di-lab practice project (Spring Boot 4.1)
package com.shoplite.lab;
import java.math.BigDecimal;
import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplicationpublic class DiLabApplication {
public static void main(String[] args) { ConfigurableApplicationContext context = SpringApplication.run(DiLabApplication.class, args);
// 1. Ask for a bean by its type PriceFormatter formatter = context.getBean(PriceFormatter.class); System.out.println("Course kit price: " + formatter.format(new BigDecimal("1499")));
// 2. Ask for the same bean by its name PriceFormatter byName = context.getBean("priceFormatter", PriceFormatter.class); System.out.println("Hostel fee: " + byName.format(new BigDecimal("42500.5")));
// 3. List the beans: all of them, then only ours System.out.println("Beans in the context: " + context.getBeanDefinitionCount()); for (String name : context.getBeanDefinitionNames()) { Class<?> type = context.getType(name); if (type != null && type.getName().startsWith("com.shoplite")) { System.out.println(" our bean: " + name); } } }}
package com.shoplite.lab;
import java.math.BigDecimal;import java.math.RoundingMode;
import org.springframework.stereotype.Component;
@Componentpublic class PriceFormatter {
public String format(BigDecimal amount) { return "Rs " + amount.setScale(2, RoundingMode.HALF_UP).toPlainString(); }}Course kit price: Rs 1499.00 Hostel fee: Rs 42500.50 Beans in the context: 51 our bean: diLabApplication our bean: priceFormatter
What this code does
- Both
getBeancalls return the bean Spring created at startup: one asks by type, the other by the namepriceFormatter. - The context holds 51 beans, but only two are ours:
diLabApplication(the main class is a bean too) andpriceFormatter. The rest belong to Spring Boot; your count may differ with another Boot version. getType(name)returns the class behind a bean name. Theifkeeps only classes fromcom.shoplitepackages.
A @Component bean is named after its class with a small first letter. getBeanDefinitionNames() lists every bean name, and containsBean(name) checks one name.
Calling getBean yourself is fine for learning and debugging. Real application classes never do it: they receive the beans they need through their constructor, as the startup runner below shows.
One shared instance: the singleton default
A singleton bean is the default scope: Spring creates one object for the bean and gives that same object to everyone who asks. Two getBean calls return the same object, so == is true.
Ask the context for the same bean twice, then make an object with new. Watch the == result and the ticket numbers.
Example 3 · TicketCounter.java, DiLabApplication.java
Runs in: the di-lab practice project (Spring Boot 4.1)
package com.shoplite.lab;
import org.springframework.stereotype.Component;
@Componentpublic class TicketCounter {
private int lastTicket = 0;
public TicketCounter() { System.out.println("TicketCounter created"); }
public int nextTicket() { lastTicket++; return lastTicket; }}
package com.shoplite.lab;
import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplicationpublic class DiLabApplication {
public static void main(String[] args) { ConfigurableApplicationContext context = SpringApplication.run(DiLabApplication.class, args);
TicketCounter first = context.getBean(TicketCounter.class); TicketCounter second = context.getBean(TicketCounter.class); System.out.println("Same object? " + (first == second)); System.out.println("Ticket from first: " + first.nextTicket()); System.out.println("Ticket from second: " + second.nextTicket());
TicketCounter mine = new TicketCounter(); // not a bean: Spring does not know it System.out.println("Same as Spring's? " + (mine == first)); System.out.println("Ticket from mine: " + mine.nextTicket()); }}TicketCounter created Same object? true Ticket from first: 1 Ticket from second: 2 TicketCounter created Same as Spring's? false Ticket from mine: 1
What this code does
TicketCounter createdprints once at startup, thoughgetBeanis called twice. Both calls return the one bean, sofirst == secondistrue.- The ticket numbers go 1, then 2 across the two variables, because both point to one object with one
lastTicketfield. new TicketCounter()runs the constructor again and makes a separate object that starts from 0. Spring has nothing to do with it.
One shared object is cheap: a service is built once at startup, not once per use. It also means a field inside a bean is shared by every user of that bean, so a counter in a bean counts for the whole app.
An object you make yourself with new is not a bean. Spring does not know about it, does not pass it any dependencies and does not share it.
Predict the output
Predict the shared bean
TicketCounter is a normal @Component. Choose what the code prints.
Round 1 of 2
Two getBean calls, then two tickets.
Running code at startup: CommandLineRunner and ApplicationRunner
A CommandLineRunner is a bean whose run(String... args) method Spring calls once, right after the context is ready. It is the clean place for start-up work: print a report, check a setting, load sample data.
Spring calls a runner's run method once, when startup is finished. StartupReport implements CommandLineRunner, and its constructor asks for the PriceFormatter bean.
Example 4 · src/main/java/com/shoplite/lab/StartupReport.java
Runs in: the di-lab practice project (Spring Boot 4.1)
package com.shoplite.lab;
import java.math.BigDecimal;
import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;
@Componentpublic class StartupReport implements CommandLineRunner {
private final PriceFormatter formatter;
public StartupReport(PriceFormatter formatter) { // Spring passes its PriceFormatter bean this.formatter = formatter; }
@Override public void run(String... args) { System.out.println("ShopLite lab started"); System.out.println("Cheapest kit: " + formatter.format(new BigDecimal("399"))); System.out.println("Costliest kit: " + formatter.format(new BigDecimal("2999.5"))); }}ShopLite lab started Cheapest kit: Rs 399.00 Costliest kit: Rs 2999.50
What this code does
StartupReportneeds aPriceFormatter, so Spring creates the formatter first and passes it to the constructor.PriceFormatteris the class from Example 2.- When every bean is ready, Spring calls
runonce. The main class is back to the plain version from Example 1: nogetBeananywhere.
Example 5 · RawArgsRunner.java, DeliveryCityRunner.java
Runs in: the di-lab practice project (Spring Boot 4.1)
package com.shoplite.lab;
import java.util.Arrays;
import org.springframework.boot.CommandLineRunner;import org.springframework.core.annotation.Order;import org.springframework.stereotype.Component;
@Component@Order(1)public class RawArgsRunner implements CommandLineRunner {
@Override public void run(String... args) { System.out.println("CommandLineRunner sees: " + Arrays.toString(args)); }}
package com.shoplite.lab;
import java.util.List;
import org.springframework.boot.ApplicationArguments;import org.springframework.boot.ApplicationRunner;import org.springframework.core.annotation.Order;import org.springframework.stereotype.Component;
@Component@Order(2)public class DeliveryCityRunner implements ApplicationRunner {
@Override public void run(ApplicationArguments args) { System.out.println("ApplicationRunner options: " + args.getOptionNames()); List<String> cities = args.getOptionValues("city"); System.out.println("Delivery cities: " + cities); System.out.println("Has --express? " + args.containsOption("express")); System.out.println("Other words: " + args.getNonOptionArgs()); }}CommandLineRunner sees: [--city=Pune, --city=Delhi, report] ApplicationRunner options: [city] Delivery cities: [Pune, Delhi] Has --express? false Other words: [report]
What this code does
- Run it with the arguments
--city=Pune --city=Delhi report: put them in the IDE run configuration (Program arguments), or package the app and runjava -jar target/di-lab-0.0.1-SNAPSHOT.jar --city=Pune --city=Delhi report. CommandLineRunnergets the raw strings.ApplicationRunnergets them parsed:cityis an option with two values,reportis a plain word, and there is no--expressoption.@Order(1)runs before@Order(2). Without@Order, never rely on any order between runners.
When a runner's constructor asks for another bean, Spring passes that bean in. This is dependency injection; the Constructor injection lesson covers it fully.
An ApplicationRunner does the same job, but run receives an ApplicationArguments object. It splits the command-line arguments into options such as --city=Pune (getOptionValues("city")) and plain words (getNonOptionArgs()). With several runners, @Order(1), @Order(2) fix the order: the lower number runs first.
NoSuchBeanDefinitionException: asking for a missing bean
NoSuchBeanDefinitionException is what Spring throws when you ask the context for a bean it does not have. The message names the missing type (No qualifying bean of type ...) or name (No bean named ... available).
SmsSender has no annotation. Ask the context for it by type and by name, and read the two messages.
Example 6 · SmsSender.java, DiLabApplication.java
Runs in: the di-lab practice project (Spring Boot 4.1)
package com.shoplite.lab;
// No @Component here, so Spring never creates this classpublic class SmsSender {
public void send(String phone, String text) { System.out.println("SMS to " + phone + ": " + text); }}
package com.shoplite.lab;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplicationpublic class DiLabApplication {
public static void main(String[] args) { ConfigurableApplicationContext context = SpringApplication.run(DiLabApplication.class, args);
System.out.println("Is there a bean named smsSender? " + context.containsBean("smsSender"));
try { context.getBean(SmsSender.class); } catch (NoSuchBeanDefinitionException e) { System.out.println("By type: " + e.getMessage()); }
try { context.getBean("smsSender"); } catch (NoSuchBeanDefinitionException e) { System.out.println("By name: " + e.getMessage()); } }}Is there a bean named smsSender? false By type: No qualifying bean of type 'com.shoplite.lab.SmsSender' available By name: No bean named 'smsSender' available
What this code does
SmsSenderhas no@Component, so Spring never made a bean of it:containsBean("smsSender")isfalseand bothgetBeancalls throw.- Without the
try, the program stops withException in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionExceptionfollowed by the same message and a stack trace. - The fix is one line: add
@Component(and its import) abovepublic class SmsSender. Then both lookups return the bean.
The usual cause is a class without @Component (or one of the annotations in the next lesson), so Spring never created it. Other causes are a typo in the bean name and a class outside the packages Spring searches. Read the class name in the message, open that class and check its annotation first.
When a missing bean is needed by another bean's constructor, the app does not even start; the next lesson shows that report.
Fix the error
Fix the missing bean
Read the real error, then pick the line that fixes it.
Round 1 of 2
Spring never creates SmsSender.
Error
No qualifying bean of type 'com.shoplite.lab.SmsSender' available
Next step
Check your understanding
12 quick questions