I have seen few examples where customized annotations were used. example
@SimpleAnnotation
class SampleBean {
@SimpleAnnotation
public String getName() {
return "AAA";
}
public void setName(String name) {
}
public int getHeight() {
return 201;
}
}
@Target( { ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@interface SimpleAnnotation {
}
Can anyone tell why we use this?
Spring supports for many Annotation the concept of “meta-annotation”. (I am not sure if it is for all.)
This mean that you can build your own annotation and annotate the annotation with one of springs “core” annotations.
For example:
Then you can use this annotation instead of
@Service. (Btw:@Service,@Repository,@Controlleruse the same technique to “inherit” from@Component)One example that make heavy use of this is “inherit” from
@Qualifier.For an example and some explanation have a look at Spring Reference Chapter: 3.9.3 Fine-tuning annotation-based autowiring with qualifiers (The Example with
@Genreis at the end of the chapter.)One very usefull construct that can be done with that technique is, that it enables you to combine several Annotations to a (in your use case) more meaning full. So instead of writing at every class of some type allways the same two annotations, for example:
@Serviceand@Qualifiyer("someting")(the org.springframework.beans.factory.annotation.Qualifier). You can create your custom annotation that is annotated with this two annotations, and then use in your beans only this one custom annotation. (@See Avoid Spring Annotation Code Smell Use Spring 3 Custom Annotations)If you want to see how powerfull this technique can be use, you can have a look at Context and Dependency Injection Framework.
Question from the comment:
The Annotations (defined by @Interface) work a bit like beans. This Fields are the properties that can/must be define if you use the annotations. The values can be later on be read via reflection API.
For example the
@ControllerAnnotation in Spring:The field with name
valueis that field that can be used without explicit name it: (@Controller("myUrl")is the same@Controller(value="myUrl"))