简体   繁体   中英

Groovy - Unable to use static final string in an annotation

Something is really wierd. I'm using a static final String in an annotation value.

class Constants {
    static final String myConstant = "ting tong"   
}

class Service {
    @CacheEvict(cacheNames = Constants.myConstant)
    void doSomethingNice() {    
    }
}

However, i just cant get it to compile.

Here's the error message

Attribute 'myConstant' should have type 'java.lang.String'; but found type 'java.lang.Object' in @org.springframework.cache.annotation.CacheEvict

Expected 'Constants.getMyConstant()' to be an inline constant of type java.lang.String in @org.springframework.cache.annotation.CacheEvict

What can be the problem? This works perfectly in Java

In general it is a good practice to keep the constants under an Interface and not under class.

interface Constants {
    public static final String myConstant = "ting tong"   
}

Another good practice is to define constants as static final not just final, because it is more efficient to create only 1 instance for each constant.

Turns out that the problem was due to the automatic getter/setter generation of Groovy. It would generate a getter for my constant and use it within the annotation, and i guess thats not allowed.

To fix, mark the field as public. That would disable the automatic getter generation.

class Constants {
    public static final String myConstant = "ting tong"   
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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