jeudi 28 septembre 2017

Annotation on a static field?

My services can define their own permissions. Each service will have a ServiceAPermissions class that extends the Permission class.

The Permission class looks like this:

public abstract class Permissions {

    @Autowired
    PermissionRegistry permissionRegistry;

    @PostConstruct
    private void init()throws IllegalArgumentException, IllegalAccessException {
        for (Field field: this.getClass().getFields()) {
            if (field.isAnnotationPresent(PermissionDefinition.class)) {
                permissionRegistry.registerNewPermissions((String)field.get(null));
            }
        }
    }

    protected static String join(String... tokens) {
        return String.join(".", tokens);
    }
}

As you see, I scan the current class (which usually will be the extending class) for members with the annotation PermissionDefinition.

A ServiceAPermissions class then would look like this:

@Configuration()
public class ServiceAPermissions extends Permissions {

    private static final String BASE = "servicea";

    @PermissionDefinition
    public static final String SERVICEA_READ = join(BASE,"read");

    @PermissionDefinition
    public static final String SERVICEA_WRITE = join(BASE,"write");
}

As I had to figure out, Annotations on static fields are not working. I do need this members to be public static.

Is there an alternative approach, which is used to solve this problem?

Or did I take a complete wrong turn somewhere?





Aucun commentaire:

Enregistrer un commentaire