Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?


2 Answers

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{}
like image 129
mahmoud fathy Avatar answered Oct 28 '25 23:10

mahmoud fathy


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{}
like image 33
Planck Constant Avatar answered Oct 29 '25 00:10

Planck Constant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!