Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
358 views
in Technique[技术] by (71.8m points)

spring - Creating and using annotation in java

I am reviewing open source spring projects. I am confused about the use of annotations around here. I want to ask to clarify this.

@Target(ElementType.METHOD)
@Retention(RUNTIME)
@Bean
public @interface Merge {

   
    @AliasFor("targetRef")
    String value() default "";
   
    @AliasFor("value")
    String targetRef() default "";

    Placement placement() default Placement.APPEND;
   
    int position() default 0;
    
    Class<MergeBeanStatusProvider> statusProvider() default MergeBeanStatusProvider.class;

    boolean early() default false;

}

An annotation has been created here named Merge. It has different parameters and default values.

@Configuration
public class LocalConfiguration {

    @Merge(targetRef = "mergedList", early = true)
    public List<String> blLocalMerge() {
        return Arrays.asList("local-config1", "local-config2");
    }
}

And this is usage of @Merge annotation in any class I choosed randomly.

When I examined the code, I could not find any class related to the implementation of Merge annotation. By the way, this problem I'm having isn't just about this annotation. Almost all the annotations I have examined are used without being implemented in any way. I think I will understand the others if we start from this annotation. What does this anotation do? What kind of message does it give to the place where it is used. How does the application understand what that annotation does in runtime without being implemented anywhere.

Thanks.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Annotations don't have implementations. They are processed by external classes or tools depending on the RetentionPolicy. In this case, the Merge annotation has Runtime retention so it will be available via reflection once the class is loaded. At runtime any interested party (in this case I assume the Spring Framework) can use getAnnotations on your LocalConfiguration class to detect the Merge annotation and take whatever action that needs to be taken. The possibilities are really up to the framework that defined the annotation. A lot of Spring injection works like this with annotations but they are also used by many other frameworks such as Hibernate, Jersey, etc. The main idea is that annotations act as markers on specific code points to be used by an external entity at a later point.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...