Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Spring Boot如何知道要注入哪个对象?_Java_Spring Boot - Fatal编程技术网

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