2011-06-07 113 views
20

是否有可能使用@Autowired列表?春天autowire列表

就像我有屬性與MIME類型,在我的類文件的文件我有這樣的事情

@Autowired 
private List<String> mimeTypes = new ArrayList<String>(); 
+5

這是已經有一段時間 - 如果任何問題的答案是有幫助的,請註明它是正確的,讓別人有同樣的問題,可以很容易地識別出任何有用的答案。的 – chzbrgla 2011-07-21 08:01:21

+1

可能重複的[自動佈線列表使用util的架構給出NoSuchBeanDefinitionException](http://stackoverflow.com/questions/1363310/auto-wiring-a-list-using-util-schema-gives-nosuchbeandefinitionexception) – skaffman 2012-02-04 12:15:58

回答

1

我認爲您至少需要限定符。而對「新」的呼籲似乎與使用Spring的想法背道而馳。你對Spring的角色感到困惑。如果你調用「new」,那麼這個對象不受Spring的控制。

+0

它只是覆蓋整個對象。春天不知道(或不關心)之前有什麼東西。 – 2011-06-07 15:15:40

+0

使用原型範圍的bean,你甚至可以使用'new'並且仍然擁有那個bean spring btw http://static.springsource.org/spring/docs/current/reference/beans.html#beans-factory-scopes - 原型 – chzbrgla 2011-06-07 15:19:07

10

您甚至可以在您的spring .xml中創建一個java.util.List,並通過@Qualifier將其注入到您的應用程序中。從SpringSource的http://static.springsource.org/spring/docs/current/reference/xsd-config.html

<!-- creates a java.util.List instance with the supplied values --> 
<util:list id="emails"> 
    <value>[email protected]</value> 
    <value>[email protected]</value> 
    <value>[email protected]</value> 
    <value>[email protected]</value> 
</util:list> 

因此,這將改變您的佈線:

@Autowired 
@Qualifier("emails") 
private List<String> mimeTypes = new ArrayList<String>(); 

因爲你反正注入一個字符串列表,我建議這種方法。

乾杯!

編輯

如果要注入的屬性,看看這個How can I inject a property value into a Spring Bean which was configured using annotations?

32

@Qualifier("..")氣餒,而是儘量自動裝配按姓名使用

private @Resource(name="..") List<Strings> mimeTypes; 

另請參閱How to autowire factorybean

+2

+1非常好的發現!我只是想弄清楚爲什麼我不能讓這個場景起作用。 – 2012-01-25 21:33:30

25

Spring 4支持自動收集給定類型的所有bean並將它們注入到集合或數組中的功能。

例子:

@Component 
public class Car implements Vehicle { 
} 

@Component 
public class Bus implements Vehicle { 
} 

@Component 
public class User { 
    @Autowired 
    List<Vehicle> vehicles;//contains car and bus 
} 

編號:Spring 4 Ordering Autowired Collections

+1

當沒有定義該類型的bean時會發生什麼?它會自動裝入一個空的列表 – user2798694 2017-01-11 21:23:38

+0

@ user2798694它應該是空的或空的。 – ThoQ 2017-01-12 01:39:54

0

如果自動裝配Autowired bean是在同一個(@Configuration)類中聲明,你需要它來聲明另一個Bean,那麼以下工作:

@Bean 
public BeanWithMimeTypes beanWithMimeTypes() { 
    return new BeanWithMimeTypes(mimeTypes()); 
} 

@Bean 
public List<String> mimeTypes() { 
    return Arrays.<String>asList("text/html", "application/json); 
} 

即使您在另一個配置中覆蓋mimeTypes bean,它也會正常運行。不需要明確的@Qualifier@Resource註釋。

+1

這只是顯示如何使用構造函數(這是可以的)。但需要指出的是,在這個例子中,不需要用@Bean來註釋mimeTypes(),除非你想讓它的結果在應用程序上下文中可用,而不是創建BeanWithMimeTypes組件。 – 2017-06-17 04:52:54