Spring Beans and Constructor Injection
When two objects implement the same interface, Spring needs a way to select the object to inject. Register a soccer ball and a basketball as separate beans, then select each by name to see how dependency injection works.
Use the Java 17 source level and Spring Boot 3.5.16 project from Spring Boot lab setup. Add the following files to that base project.
Beans and dependency injection
Section titled “Beans and dependency injection”A bean is an object whose creation and dependencies are managed by the Spring container. A class that receives implementations through its constructor leaves the choice of implementation to the container configuration. This is dependency injection (DI).
@Component registers a bean through classpath scanning, while @Bean registers a method return value from a @Configuration class. This example uses @Bean to configure two implementations of one interface explicitly.
Register two beans
Section titled “Register two beans”package com.example.tutorial;
public interface Ball { String touchBall();}package com.example.tutorial;
import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;
@Configurationpublic class BallConfiguration { @Bean("soccerBall") Ball soccerBall() { return () -> "soccer"; }
@Bean("basketBall") Ball basketBall() { return () -> "basket"; }}The explicit names soccerBall and basketBall replace the default method names as bean names. @Qualifier narrows injection candidates; it does not register a bean or rename one.
Inject through the constructor and return the result
Section titled “Inject through the constructor and return the result”package com.example.tutorial;
import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.stereotype.Component;
@Componentpublic class Player { private final Ball soccerBall; private final Ball basketBall;
public Player(@Qualifier("soccerBall") Ball soccerBall, @Qualifier("basketBall") Ball basketBall) { this.soccerBall = soccerBall; this.basketBall = basketBall; }
public String touch() { return soccerBall.touchBall() + "," + basketBall.touchBall(); }}The class has a single constructor, so constructor injection works without @Autowired. Each parameter has a @Qualifier because there are two beans of type Ball. The touch() method combines and returns both results. A method declared to return String cannot end after calling other methods without returning a value.
Check the return value and singleton scope
Section titled “Check the return value and singleton scope”package com.example.tutorial;
import org.junit.jupiter.api.Test;import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
class PlayerTest { @Test void returnsBothQualifiedBeans() { try (var context = new AnnotationConfigApplicationContext( BallConfiguration.class, Player.class)) { assertThat(context.getBean(Player.class).touch()) .isEqualTo("soccer,basket"); } }
@Test void reusesSingletonWithinTheSameContext() { try (var context = new AnnotationConfigApplicationContext( BallConfiguration.class)) { assertThat(context.getBean("soccerBall")) .isSameAs(context.getBean("soccerBall")); } }}mvn test -Dtest=PlayerTestThe first test expects soccer,basket. The second checks that looking up the same name twice within one container returns the same object. Two containers can each have their own singleton instance.
Scopes and lifecycle
Section titled “Scopes and lifecycle”| Scope | Creation and sharing boundary | Consideration |
|---|---|---|
singleton | One instance per bean definition in a container | Multiple requests can access the same object |
prototype | A new instance on each request to the container | Injecting it once into a singleton retains that reference |
request | One object per HTTP request | Requires a web context |
session | One object per HTTP session | Requires a web context |
application | One object per ServletContext | Its boundary differs from a regular singleton |
Use jakarta.annotation.PostConstruct for initialization after bean creation and jakarta.annotation.PreDestroy for cleanup before normal container shutdown. The container does not manage a prototype bean through destruction, so its user must release any resources it owns.
Scope of this example
Section titled “Scope of this example”The beans only return strings and hold no request state. Storing per-user data in singleton fields can mix data across requests. Pass request-specific values as method arguments or manage them within the appropriate request scope. Before adding more names for complex selection logic, decide which component should select the implementation.