[英]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 编译器插件,您只需覆盖自定义ClassBuilder
的newField
方法:
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.