英文:
How does Spring Boot know which object to inject?
问题
Spring Boot是如何知道要将哪种类型的Vehicle放入我的Student对象中的呢?
我知道Guice有Modules,它们通过@Provides和@Singleton以及在需要该对象的类中使用@Inject来定义某个对象的构建方式。
Spring Boot是否也有类似的功能呢?
英文:
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?
答案1
得分: 1
是的
@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{}
英文:
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{}
答案2
得分: 1
为了访问相同类型的Bean,通常我们使用@Qualifier("beanName")
注解。
@Data
@Component
public class Student {
@Autowired
@Qualifier("Jeep")
private Vehicle vehicle;
}
public interface Vehicle {}
@Component
@Qualifier("Jeep")
public class Jeep implements Vehicle {}
@Component
@Qualifier("Van")
public class Van implements Vehicle {}
你还可以使用@Primary
注解来标注默认的Bean,这样如果没有使用限定符的话,将选择这个Bean。
@Data
@Component
public class Student {
@Autowired
private Vehicle vehicle;
}
public interface Vehicle {}
@Component
@Primary
public class Jeep implements Vehicle {}
@Component
public class 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{}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论