春天的绑定注释
我们正在使用guice进行依赖注入。
现在我们要使用Spring Boot编写新项目。由于我们使用的是Spring Boot,因此我们认为最好使用Spring进行依赖注入而不是使用guice。
We are using guice for dependency injection. Now we want to write new project using spring boot. Since we are using Spring Boot, we think it is better to use Spring for dependency injection instead of guice.
在guice中,我们使用了绑定注释。如果我们有多个bean,并且可以根据注释将其注入,这将非常有用。
In guice we used Binding Annoation. This is very useful if we have multiple beans available and it can be injected according the annotations.
类似于Spring中的功能吗?我们是否需要相应地命名bean并将其与 @Autowire
和 @Qualifier
一起使用?
Similar to that what we have in Spring? Do we need to name the bean accordingly and use it with @Autowire
and @Qualifier
?
您可以使用 @Autowired
@Autowired
private MyBean myBean;
对于许多bean示例配置类:
For many beans example configuration class:
@Configuration
public class MyConfiguration {
@Bean(name="myFirstBean")
public MyBean oneBean(){
return new MyBean();
}
@Bean(name="mySecondBean")
public MyBean secondBean(){
return new MyBean();
}
}
@Autowired
和 @Qualifier( someName)
一起使用时,如果您有多个类型的bean并且想要一些特定的bean。
@Autowired
with @Qualifier("someName")
when you have more than one bean of some type and you want some specific.
@Autowired
@Qualifier("myFirstBean")
private MyBean myFirstBean;
@Autowired
@Qualifier("mySecondBean")
private MyBean mySecondBean;
想要注入所有相同类型的豆时,您可以:
When you want inject all beans of the same type you can:
@Autowired
private List<MyBean> myBeans;