簡體   English   中英

如何在 Java 或 Kotlin 中用我自己的注釋包裝 @Column 注釋

[英]How to wrap @Column annotation with my own annotation in Java or Kotlin

我只是想擁有自己的注釋來清理注釋質量並能夠在需要時輕松更改它們;

import javax.persistence.Column
import javax.validation.constraints.Size
class Foo(){
    @Column(name="bar_", nullable = false, length = 32)
    @Size(min = 32, max = 32)
    String bar;

    @Column(nullable = false, length = 32)
    @Size(min = 32, max = 32)
    String bas;

    @Column(nullable = false, length = 32, unique=true)
    @Size(min = 32, max = 32)
    String baq;
}

希望我能

class Foo(){
    @MyColumn(name="bar_")
    String bar;

    @MyColumn
    String bas;

    @MyColumn(unique=true)
    String baq;
}

nullable = false, length = 32是默認參數。

歡迎使用 Java 或 Kotlin 解決方案。

由於您使用的是從javax導入的 3-rd 方注釋,因此最好的選擇是引入復合注釋。 (Kotlin 不支持注解 inheritance。

@Column(name = "bar_", nullable = false, length = 32)
@Size(min = 32, max = 32)
annotation class Anno

Spring 引導將大量配置注釋組合在一起做得非常好 - 檢查一下

復合注釋Anno存在問題。 您必須提供具有常量值的注釋參數。

如果你確定,你需要一個參數化的注釋,比如

@Column(...)
@Size(min = Anno.max, max = Anno.min)
annotation class Anno(val min: Int, val max: Int)

看看Kapt或 Kotlin 編譯器插件,您將需要一段代碼生成。

使用 Kapt 或 Kotlin 編譯器插件,您只需覆蓋自定義ClassBuildernewField方法:

  override fun newField(
      origin: JvmDeclarationOrigin,
      access: Int,
      name: String,
      desc: String,
      signature: String?,
      value: Any?
  ): FieldVisitor {
    // if field is annotated with Anno -- add two custom annotation with parameters of your choice
    // otherwise perform a standard field init
  }

然后注冊它

class AnnoRegister : ComponentRegistrar {
  override fun registerProjectComponents(
      project: MockProject,
      configuration: CompilerConfiguration
  ) {
    ...
  }

將此處理集成到現有的 gradle 或 maven 項目中應該相對容易,或者只是傳遞給kotlinc

對於您可以使用的尺寸

@Size(min = 32, max = 32)
@Inherited
annotation class DefaultSize()

然而,超級的動態參數,比如@Column中的name會使事情變得有點復雜。 我相信您需要為此進行某種運行時注釋修改,請參閱更改注釋參數運行時

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM