简体   繁体   English

Grails:将注释应用于属性访问器而不是字段

[英]Grails: applying annotations to property accessors instead of field

In Grails, is it possible to apply annotations to properties' accessors instead of (or in addition to) its field, without explicitly defining the accessors? 在Grails中,是否可以在属性的访问器中(而不是在其字段之外)应用注释,而无需明确定义访问器?

If so, what version of Grails is required? 如果是这样,需要什么版本的Grails?

eg, I'd like something like the following (using a fake syntax that uses specific labels to determine what to apply annotations to): 例如,我想要类似以下内容(使用使用特定标签的假语法来确定将注释应用于哪些内容):

class C {
    field:
    @A1
    getter:
    @A2
    getter:
    @A3
    accessors:
    @A4
    all:
    @A5
    String p
}

When you define a property in a POGO like a Grails domain class, the Groovy compiler rewrites it as a private field with a getter and a setter, but only if there's no scope modifier ( public / protected /etc.) 当您在POGO中定义诸如Grails域类的属性时,Groovy编译器会将其重写为带有getter和setter的私有字段,但前提是没有范围修饰符( public / protected / etc。)。

This is convenient because if you later want to add logic or calculations when setting and/or getting the value, you can add your own getter and/or setter method and the compiler will only generate methods that aren't already explicitly defined. 这很方便,因为如果以后要在设置和/或获取值时添加逻辑或计算,则可以添加自己的getter和/或setter方法,并且编译器将仅生成尚未明确定义的方法。 Java classes will have been using the getters and setters already, so this doesn't affect existing clients or require recompiling. Java类已经在使用getter和setter了,因此这不会影响现有的客户端,也不需要重新编译。

You can see by decompiling your domain class that the Groovy compiler moves any annotations defined on properties to the fields, so for example with this domain class 通过反编译您的域类,您可以看到Groovy编译器将属性定义的所有注释移至字段,例如,使用该域类

class Thing {
   @Foo
   String name
}

you'll see code similar to this in the decompiled code: 您将在反编译的代码中看到与此类似的代码:

@Foo
private String name;

public String getName() {
   return name;
}

public void setName(String name) {
   this.name = name
}

Many frameworks will access field annotations or accessor annotations, so often this works without any additional configuration, but it depends on the framework or code that's reading the annotations. 许多框架将访问字段批注或访问者批注,因此通常无需任何其他配置即可工作,但这取决于读取批注的框架或代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM