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
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:
@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 |
@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:
@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:
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:
shop.pricing.tax-rate=0.18
shop.pricing.currency=INR
shop.pricing.free-shipping-from=999@ConfigurationProperties(prefix = "shop.pricing")
public record PricingProperties(BigDecimal taxRate, String currency, int freeShippingFrom) {}Enable scanning for them once, on the application class:
@SpringBootApplication
@ConfigurationPropertiesScan
public class ShopApplication { … }Then inject the properties like any other bean:
@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());
}
}curl "localhost:8080/api/price?net=100"{"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:
@Configuration
@Profile("dev")
class DevDataConfig {
@Bean CommandLineRunner seedDemoData(ProductRepository repo) { … } // only in development
}java -jar shop.jar --spring.profiles.active=devRunning 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:
@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
- Add a
shop.pricing.max-discountproperty (a percentage) and expose it through/api/price. - Create a
Clockbean and inject it into a service that returns "Good morning" or "Good evening". - Write two
NotificationSenderimplementations (email and SMS), mark one@Primary, and inject the other with@Qualifier.
1.What is a Spring bean?
2.Why is constructor injection preferred over field injection?
3.What does @ConfigurationProperties(prefix = "shop.pricing") do?