2011-08-21 46 views
9

是否有可能做同樣的使用註釋驅動注射:Spring框架是否有可能以註釋驅動的方式注入集合?

 
<beans> 
... 
    <bean id="interceptorsList" class="com.mytest.AnyAction"> 
     <property name="interceptors"> 
      <list> 
       <ref bean="validatorInteceptor"/> 
       <ref bean="profilingInterceptor"/> 
      </list> 
     </property> 
    </bean> 
</beans> 

是否有可能做使用註釋驅動注射一樣嗎?

回答

4

好問題 - 我不這麼認爲(假設通過「註解驅動注入」,你指的是AnyAction上的註釋)。

這有可能是以下可能的工作,但我不認爲春季識別@Resources註釋:

@Resources({ 
    @Resource(name="validatorInteceptor"), 
    @Resource(name="profilingInterceptor") 
}) 
private List interceptors; 

給它一個想試試,你永遠不知道。

除此之外,你可以使用@Configuration風格的配置,而不是XML:

@Configuration 
public class MyConfig { 

    private @Resource Interceptor profilingInterceptor; 
    private @Resource Interceptor validatorInteceptor; 

    @Bean 
    public AnyAction anyAction() { 
     AnyAction anyAction = new AnyAction(); 
     anyAction.setInterceptors(Arrays.asList(
     profilingInterceptor, validatorInteceptor 
    )); 
     return anyAction; 
    } 
} 
+0

@Resources僅適用於類型,不適用於字段。 似乎是否有如此簡單的方式來表示XML中的列表,應該有一種方法可以對註釋做同樣的處理。這是令人失望的。 – Cameron

1

是的,春天會很高興,如果你使用這種模式注入所有配置的攔截器:

@Autowired 
public void setInterceptors(List<Interceptor> interceptors){ 
    this.interceptors = interceptors; 
} 
private List<Interceptor> interceptors; 

請注意,您可能必須在context.xml中配置default-autowire = byType。我不知道在簡單的註釋配置中是否有替代方案。

相關問題