Skip to content

Spring Beans and Constructor Injection

Interactive Diagram

새 탭 ↗

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.

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.

src/main/java/com/example/tutorial/Ball.java
package com.example.tutorial;
public interface Ball {
String touchBall();
}
src/main/java/com/example/tutorial/BallConfiguration.java
package com.example.tutorial;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public 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”
src/main/java/com/example/tutorial/Player.java
package com.example.tutorial;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
@Component
public 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”
src/test/java/com/example/tutorial/PlayerTest.java
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"));
}
}
}
Terminal window
mvn test -Dtest=PlayerTest

The 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.

ScopeCreation and sharing boundaryConsideration
singletonOne instance per bean definition in a containerMultiple requests can access the same object
prototypeA new instance on each request to the containerInjecting it once into a singleton retains that reference
requestOne object per HTTP requestRequires a web context
sessionOne object per HTTP sessionRequires a web context
applicationOne object per ServletContextIts 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.

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.