Java Spring Boot如何知道要注入哪个对象?
假设我有以下几节课Java Spring Boot如何知道要注入哪个对象?,java,spring-boot,Java,Spring Boot,假设我有以下几节课 @数据 @组成部分 公立班学生{ @自动连线 私家车; } 公共接口车辆{} @组成部分 公共吉普车{} @组成部分 公共货车{} Spring Boot如何知道将哪种类型的车辆放入我的学生对象中 我知道Guice有一些模块,它们精确地定义了在需要对象的类中如何使用@Provides和@Singleton以及@Inject来构建某个对象 弹簧靴有相同的功能吗?简短回答:有 @Component public class Student { @Autowir
@数据
@组成部分
公立班学生{
@自动连线
私家车;
}
公共接口车辆{}
@组成部分
公共吉普车{}
@组成部分
公共货车{}
Spring Boot如何知道将哪种类型的车辆放入我的学生对象中
我知道Guice有一些模块,它们精确地定义了在需要对象的类中如何使用@Provides和@Singleton以及@Inject来构建某个对象
弹簧靴有相同的功能吗?简短回答:有
@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{}
为了访问具有相同类型的bean,我们通常使用@Qualifier(“beanName”)注释
@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{}
您可以用@Primary注释您的默认bean,这样,如果没有限定符,就会选择这个bean
@Data
@Component
public class Student {
@Autowired
private Vehicle vehicle;
}
public interface Vehicle{}
@Component
@Primary
public Jeep implements Vehicle{}
@Component
public Van implements Vehicle{}