春天的绑定注释 [英] Binding Annotation in spring

查看:71
本文介绍了春天的绑定注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在使用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;

这篇关于春天的绑定注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆