【问题标题】:Does Spring framework makes possible to inject a collection in annotation-driven fashion?Spring 框架是否可以以注释驱动的方式注入集合?
【发布时间】:2023-04-05 09:26:02
【问题描述】:

是否可以使用注解驱动注入来做同样的事情:

... 列表> 属性> 豆>

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

【问题讨论】:

    标签: spring dependency-injection inversion-of-control


    【解决方案1】:

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

    以下可能会起作用,但我认为 Spring 无法识别 @Resources 注释:

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

    还是试试吧,你永远不知道。

    除此之外,您可以使用@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;
       }
    }
    

    【讨论】:

    • @Resources 仅适用于类型,不适用于字段。似乎如果有这样一种简单的方法可以在 XML 中表达列表,那么应该有一种方法可以对注释做同样的事情。这令人失望。
    【解决方案2】:

    是的,如果你使用这种模式,Spring 会很高兴地注入所有配置的拦截器:

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

    请注意,您可能必须在您的 context.xml 中配置 default-autowire=byType。我不知道在普通注释配置中是否有替代方案。

    【讨论】:

      猜你喜欢
      • 2019-11-30
      • 2012-10-26
      • 1970-01-01
      • 2016-02-04
      • 2011-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多