0

Is there a way I can do something like that in CDI:

@Target({ElementType.FIELD, ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface ServerConfiguration {

  @Nonbinding String url() default "http://localhost:8080";

  @Nonbinding String username() default "";

  @Nonbinding String password() default "";

}

And then define a second annotation similar to that:

@Target({ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@ServerConfiguration(username = "abc123")
public @interface MainServer {

}

To have the possibility to have a single producer for the server configuration, but to have the possibility to specify different default configurations?

The server configuration is just an example, but it shows what I mean. Basically a general qualifier that can be specialized if needed.

Thank you!

JDC
  • 4,247
  • 5
  • 31
  • 74

1 Answers1

0

This is not CDI/Qualifier specific, its a Java annotation issue. You can get the annotation's annotations and then read the values. Here is a small example:

@MainServer
public String annotatedField = "nn";

Field field = getClass().getField("annotatedField");
MainServer server = field.getAnnotation(MainServer.class);

ServerConfiguration configuration = server.annotationType().getAnnotation(ServerConfiguration.class);

String url = configuration.url(); // localhost:8080
String username = configuration.username(); // abc123
Jan Galinski
  • 11,768
  • 8
  • 54
  • 77