user12530264
user12530264

Reputation:

How does Spring Boot know which object to inject?

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?

Upvotes: 4

Views: 528

Answers (2)

mahmoud fathy
mahmoud fathy

Reputation: 78

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{}

Upvotes: 2

Planck Constant
Planck Constant

Reputation: 1524

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{}

Upvotes: 1

Related Questions