2011-08-21 126 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。我不知道在简单的注释配置中是否有替代方案。

相关问题