2016-03-28 88 views
0

我們使用guice進行依賴注入。 現在我們想用spring引導來編寫新的項目。由於我們使用的是spring引導,我們認爲使用spring來進行依賴注入比替代guice更好。彈簧中的綁定註釋

在guice中我們使用了Binding Annoation。如果我們有多個可用的bean並且可以根據註釋注入,這非常有用。

類似於我們在春天有什麼?我們是否需要相應地命名bean並將其與@Autowire和@Qualifier結合使用?

回答

1

您可以使用 @Autowired當你有某種類型的bean。

@Autowired 
private MyBean myBean; 

多年豆子例如配置類:

@Configuration 
public class MyConfiguration { 

@Bean(name="myFirstBean") 
public MyBean oneBean(){ 
    return new MyBean(); 
} 

@Bean(name="mySecondBean") 
public MyBean secondBean(){ 
    return new MyBean(); 
} 
} 

與@Qualifier(「someName」),當你有一些類型的多個豆,你想一些具體的@Autowired。

@Autowired 
@Qualifier("myFirstBean") 
private MyBean myFirstBean; 

@Autowired 
@Qualifier("mySecondBean") 
private MyBean mySecondBean; 

當你想注入相同的類型,你可以在所有的bean:

@Autowired 
private List<MyBean> myBeans; 
1

第一手例如:

public class MovieRecommender { 

private final CustomerPreferenceDao customerPreferenceDao; 

@Autowired 
private MovieCatalog movieCatalog; 

@Autowired 
public MovieRecommender(CustomerPreferenceDao customerPreferenceDao) { 
    this.customerPreferenceDao = customerPreferenceDao; 
} 
// ... 
} 

這是要求Spring框架,即豆類和扶養注射非常基本的概念問題。

我會建議運行一個樣例項目,如kickstart-sample,並在玩代碼時熟悉Spring。

然後跳到官方文檔以供參考也不錯。因爲使用註釋時有更多選項需要注意。

http://docs.spring.io/spring/docs/4.3.0.BUILD-SNAPSHOT/spring-framework-reference/htmlsingle/#beans-autowired-annotation

+0

這是簡單的自動裝配。我的問題是通過應用程序上下文中的多個可用的自動裝配。 https://github.com/google/guice/wiki/BindingAnnotations#binding-annotations可以做到這一點。類似於我們可以在Spring中使用它的東西 – sag