Spring框架是否可以以注释驱动的方式注入集合?

dav*_*rmi 9 spring dependency-injection inversion-of-control

是否可以使用注释驱动注入执行相同操作:

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

是否可以使用注释驱动注射来做同样的事情?

ska*_*man 4

好问题 - 我不这么认为(假设通过“注释驱动注入”您指的是 上的注释AnyAction)。

以下内容可能有效,但我认为 Spring 无法识别该@Resources注释:

@Resources({
   @Resource(name="validatorInteceptor"),
   @Resource(name="profilingInterceptor")
})
private List interceptors;
Run Code Online (Sandbox Code Playgroud)

无论如何,尝试一下,你永远不会知道。

除此之外,您可以使用@Configuration-style 配置而不是 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;
   }
}
Run Code Online (Sandbox Code Playgroud)