【问题标题】:Applying same annotation on multiple fields在多个字段上应用相同的注释
【发布时间】:2011-03-07 08:22:37
【问题描述】:

是否可以在多个字段上应用相同的注释(如果有很多私有字段并且将它们全部注释起来看起来很尴尬。

所以我所拥有的就像

@Autowired private BlahService1 blahService1;
@Autowired private BlahService2 blahService2;
@Autowired private BlahService3 blahService3;

等等

我尝试了以下方法,但它不起作用

@Autowired{     
   private BlahService1 blahService1;       
   private BalhService2 blahService2;   
}

也许有一些喜欢自定义注释的东西?

【问题讨论】:

  • 如果字段太多以至于无法全部注释,那么您的字段可能太多了。
  • 它适用于相同类型的字段,但在这里可能没有意义。

标签: java spring annotations


【解决方案1】:

不,但你可以注释你的构造函数而不是你的字段。通过在构造要测试的实例时注入模拟依赖项(这是依赖注入有用的主要原因),这将具有使您的类更容易测试的额外好处:

@Autowired
public MyClass(BlahService1 blahService1, BlahService2 blahService2, BlahService3 blahService3) {
    this.blahService1 = blahService1;
    this.blahService2 = blahService2;
    this.blahService3 = blahService3;
}

【讨论】:

    【解决方案2】:

    该语言没有内置允许这种多注释的内容。

    然而,许多框架选择在类级别允许某种“默认注释”。

    例如,框架可以允许在类级别使用@Autowired 注释来暗示每个字段都应该是自动连接的。然而,这完全取决于要实现的框架。

    【讨论】:

      【解决方案3】:

      您可以尝试通过设置字段的默认值,将其目标类型设置为字段来扩展 AutoWired 注释接口,并且在不需要时,您可以通过仅将适当的值传递给这些字段的注释来关闭它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-05-29
        • 1970-01-01
        • 1970-01-01
        • 2023-03-16
        • 2014-08-15
        • 1970-01-01
        • 1970-01-01
        • 2021-10-22
        相关资源
        最近更新 更多