Skip to lesson

Beans and the application context

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)

PriceFormatter.javaJava
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);    }}
Output
PriceFormatter created by Spring

What this code does

  • @Component marks PriceFormatter as a bean. No line in the code calls new PriceFormatter(), yet the constructor ran: Spring created the object inside SpringApplication.run.
  • @SpringBootApplication on the main class makes Spring look for @Component classes in com.shoplite.lab and its sub-packages. The How Spring Boot Works module explains this search (component scanning).
  • The println in 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.

di-lab has no web server, so it starts, runs your code and stops. Every run takes a second or two.

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.

Spring scans the classes marked with @Component and creates one bean from each. The beans live in the application context. PriceFormatter becomes the shared bean priceFormatter. StartupReport needs a PriceFormatter, so Spring passes the priceFormatter bean to its constructor.

Example 2 · DiLabApplication.java, PriceFormatter.java

Runs in: the di-lab practice project (Spring Boot 4.1)

DiLabApplication.javaJava
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();    }}
Sample output
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 getBean calls return the bean Spring created at startup: one asks by type, the other by the name priceFormatter.
  • The context holds 51 beans, but only two are ours: diLabApplication (the main class is a bean too) and priceFormatter. The rest belong to Spring Boot; your count may differ with another Boot version.
  • getType(name) returns the class behind a bean name. The if keeps only classes from com.shoplite packages.

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.

Spring Boot registers dozens of its own beans too: 51 in di-lab with Boot 4.1.1. The number changes with the Boot version and the starters you add.

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)

TicketCounter.javaJava
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());    }}
Output
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 created prints once at startup, though getBean is called twice. Both calls return the one bean, so first == second is true.
  • The ticket numbers go 1, then 2 across the two variables, because both point to one object with one lastTicket field.
  • 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.

TicketCounter a = context.getBean(TicketCounter.class);
TicketCounter b = context.getBean(TicketCounter.class);
System.out.println(a == b);
System.out.println(a.nextTicket() + " " + b.nextTicket());
The Bean scopes lesson shows the other scopes, and the bugs a shared field causes when many users hit a web app at once.

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)

StartupReport.javaJava
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")));    }}
Output
ShopLite lab started
Cheapest kit: Rs 399.00
Costliest kit: Rs 2999.50

What this code does

  • StartupReport needs a PriceFormatter, so Spring creates the formatter first and passes it to the constructor. PriceFormatter is the class from Example 2.
  • When every bean is ready, Spring calls run once. The main class is back to the plain version from Example 1: no getBean anywhere.

Example 5 · RawArgsRunner.java, DeliveryCityRunner.java

Runs in: the di-lab practice project (Spring Boot 4.1)

RawArgsRunner.javaJava
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());    }}
Output
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 run java -jar target/di-lab-0.0.1-SNAPSHOT.jar --city=Pune --city=Delhi report.
  • CommandLineRunner gets the raw strings. ApplicationRunner gets them parsed: city is an option with two values, report is a plain word, and there is no --express option.
  • @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)

SmsSender.javaJava
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());        }    }}
Output
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

  • SmsSender has no @Component, so Spring never made a bean of it: containsBean("smsSender") is false and both getBean calls throw.
  • Without the try, the program stops with Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException followed by the same message and a stack trace.
  • The fix is one line: add @Component (and its import) above public 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.

public class SmsSender {
public void send(String phone, String text) {
System.out.println("SMS to " + phone);
}
}

Error

No qualifying bean of type 'com.shoplite.lab.SmsSender' available
Interview angle: "bean not found" questions usually expect three causes: missing annotation, wrong package, wrong name or type.

Next step

Check your understanding

12 quick questions