How does Spring Boot know which object to inject?

Viewed 211

Lets say I have the following classes

@Data
@Component
public class Student {
    
    @Autowired
    private Vehicle vehicle;

}


public interface Vehicle{}

@Component
public Jeep implements Vehicle{}

@Component
public Van implements Vehicle{}

How does Spring Boot know which type of Vehicle to put in my Student object?

I know Guice has Modules which defines exactly how a certain object is built with @Provides and @Singleton coupled with @Inject in the classes that require the object.

Does Spring Boot have the same thing?

2 Answers

Short answer: Yes

@Component
public class Student {
    
    @Autowired
    @Qualifier("jeep")
    private Vehicle vehicle;

}

public interface Vehicle{}

@Component("jeep")
public Jeep implements Vehicle{}

@Component("van")
public Van implements Vehicle{}

To access beans with the same type we usually use @Qualifier(“beanName”) annotation.

@Data
@Component
public class Student {
    @Autowired
    @Qualifier("Jeep")
    private Vehicle vehicle;
}


public interface Vehicle{}

@Component
@Qualifier("Jeep")
public Jeep implements Vehicle{}

@Component
@Qualifier("Van")
public Van implements Vehicle{}

and you can annotate your default bean with @Primary so that if no qualifier is there this bean will be selected

@Data
@Component
public class Student {
    @Autowired
    private Vehicle vehicle;
}


public interface Vehicle{}

@Component
@Primary
public Jeep implements Vehicle{}

@Component
public Van implements Vehicle{}
Related