Spring Boot如何知道要注入哪个对象?

huangapple go评论76阅读模式
英文:

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

huangapple
  • 本文由 发表于 2020年8月5日 16:46:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/63261516.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定