Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

SB
Spring Boot
0/10 completed
Beginner
Spring Boot setupControllers and RESTBeans and dependency injection
Intermediate
Spring Data JPAValidation and error handlingTesting Spring Boot apps
Advanced
Spring SecurityRelationships, paging and migrationsMicroservices with Spring
Pro
Production-ready Spring Boot
Tracks / Spring Boot / Beginner

Beans and dependency injection

At the heart of Spring is the IoC container (Inversion of Control): instead of your classes creating the objects they need with new, Spring creates them, wires them together and hands them over. Those managed objects are called beans, and handing them over is dependency injection (DI). It's what makes Spring apps easy to configure, extend and test.

The problem DI solves

java
public class OrderService {
    private final PaymentGateway gateway = new StripeGateway("sk_live_…");   // hard-wired
    private final EmailSender email = new SmtpEmailSender("smtp.example.com");
}

This class decides which payment provider, which email server and which keys to use. To test it you'd charge real cards; to switch providers you'd edit its code. With DI, the class only declares what it needs:

java
@Service
public class OrderService {
    private final PaymentGateway gateway;
    private final EmailSender email;

    public OrderService(PaymentGateway gateway, EmailSender email) {   // constructor injection
        this.gateway = gateway;
        this.email = email;
    }
}

Spring finds a bean of each type and passes it in. In tests, you pass fakes.

Declaring beans

Stereotype annotations

Classes annotated with one of these are found by component scanning and become beans:

Annotation Use for
@Component Any Spring-managed class
@Service Business logic
@Repository Data access (also translates database exceptions)
@RestController / @Controller Web endpoints
@Configuration Classes that define beans with @Bean methods
java
@Service
@Transactional(readOnly = true)
public class ProductService {

    private final ProductRepository products;

    public ProductService(ProductRepository products) {     // Spring injects the repository
        this.products = products;
    }

    public Product findById(Long id) {
        return products.findById(id).orElseThrow(() -> new ProductNotFoundException(id));
    }
}

With a single constructor, no annotation is needed: Spring uses it automatically. Prefer constructor injection: dependencies are final, the object is always fully initialised, and tests can call the constructor directly. (Field injection with @Autowired on a field still works, but hides dependencies and makes testing harder.)

@Bean methods

For classes you don't own (library classes) or that need custom setup, write a @Bean method in a @Configuration class:

java
@Configuration
public class ClientsConfig {

    @Bean
    RestClient catalogClient(RestClient.Builder builder) {
        return builder.baseUrl("https://catalog.internal").build();
    }

    @Bean
    Clock clock() {
        return Clock.systemUTC();          // inject a Clock so tests can freeze time
    }
}

Choosing between implementations

If several beans match a type, tell Spring which one you want:

java
public interface PaymentGateway { String charge(BigDecimal amount); }

@Component @Primary
class StripeGateway implements PaymentGateway { … }      // the default choice

@Component("razorpay")
class RazorpayGateway implements PaymentGateway { … }

@Service
class CheckoutService {
    CheckoutService(PaymentGateway defaultGateway, @Qualifier("razorpay") PaymentGateway indiaGateway) { … }
}

Spring can also inject all implementations at once: List<PaymentGateway> gateways.

Bean scope

By default every bean is a singleton: one instance shared by the whole application. That's why beans should be stateless (no per-request data in fields), and safe to use from many threads at once.

Configuration properties

Typed configuration is the cleanest way to give beans their settings. Define a record and bind a prefix of application.properties to it:

properties
shop.pricing.tax-rate=0.18
shop.pricing.currency=INR
shop.pricing.free-shipping-from=999
java
@ConfigurationProperties(prefix = "shop.pricing")
public record PricingProperties(BigDecimal taxRate, String currency, int freeShippingFrom) {}

Enable scanning for them once, on the application class:

java
@SpringBootApplication
@ConfigurationPropertiesScan
public class ShopApplication { … }

Then inject the properties like any other bean:

java
@Component
public class PriceCalculator {

    private final PricingProperties props;

    public PriceCalculator(PricingProperties props) {
        this.props = props;
    }

    public String withTax(BigDecimal net) {
        BigDecimal gross = net.multiply(BigDecimal.ONE.add(props.taxRate())).setScale(2, RoundingMode.HALF_UP);
        return gross + " " + props.currency();
    }
}

@RestController
public class PricingController {

    record PriceQuote(BigDecimal net, String gross, int freeShippingFrom) {}

    private final PriceCalculator calculator;
    private final PricingProperties props;

    public PricingController(PriceCalculator calculator, PricingProperties props) {
        this.calculator = calculator;
        this.props = props;
    }

    @GetMapping("/api/price")
    public PriceQuote price(@RequestParam BigDecimal net) {
        return new PriceQuote(net, calculator.withTax(net), props.freeShippingFrom());
    }
}
bash
curl "localhost:8080/api/price?net=100"
Output
{"net":100,"gross":"118.00 INR","freeShippingFrom":999}

Note how Spring's relaxed binding mapped tax-rate in the file to taxRate in Java, and converted the text 0.18 to a BigDecimal. Set SHOP_PRICING_TAX_RATE=0.05 as an environment variable and the same JAR uses 5%.

For single values you can also use @Value("${shop.pricing.currency}") on a constructor parameter, but @ConfigurationProperties is type-safe, groups related settings, and can be validated with @Validated.

Profiles

Beans and settings can be limited to an environment:

java
@Configuration
@Profile("dev")
class DevDataConfig {
    @Bean CommandLineRunner seedDemoData(ProductRepository repo) { … }    // only in development
}
bash
java -jar shop.jar --spring.profiles.active=dev

Running code at startup

A CommandLineRunner bean runs once after the application starts. Put it in its own @Component (not as a @Bean method on the main class) so that test slices, which load only part of the application, don't try to create it:

java
@Component
class SampleData implements CommandLineRunner {

    private final ProductRepository products;

    SampleData(ProductRepository products) {
        this.products = products;
    }

    @Override
    public void run(String... args) {
        if (products.count() == 0) {
            products.save(new Product("Laptop", new BigDecimal("899.00"), 15, "electronics"));
            products.save(new Product("Mug", new BigDecimal("8.99"), 200, "kitchen"));
            products.save(new Product("Teapot", new BigDecimal("34.50"), 0, "kitchen"));
        }
    }
}

(That advice comes from experience: while preparing this track, a seed method on the main class broke the web-layer tests with "No qualifying bean of type 'ProductRepository' available".)

Practice

  1. Add a shop.pricing.max-discount property (a percentage) and expose it through /api/price.
  2. Create a Clock bean and inject it into a service that returns "Good morning" or "Good evening".
  3. Write two NotificationSender implementations (email and SMS), mark one @Primary, and inject the other with @Qualifier.
✎ Check your understanding

1.What is a Spring bean?

2.Why is constructor injection preferred over field injection?

3.What does @ConfigurationProperties(prefix = "shop.pricing") do?

← Controllers and REST