Search code examples
javaspringannotationsautowiredspring-annotations

@Autowired usage in Annotation type declaration


I understand @Autowired used for dependency injection

Marks a constructor, field, setter method or config method as to be autowired by Spring's dependency injection facilities.

But what's the usage for Annotation type declaration that is defined

@Target(value={CONSTRUCTOR,METHOD,PARAMETER,FIELD,ANNOTATION_TYPE})

Is there any usage/effect for defining @Autowired in custom annotation:

@Autowired
public @interface MyAnnotation {
}

I didn't find any references in Spring docs

By default, the autowiring will fail whenever zero candidate beans are available; the default behavior is to treat annotated methods, constructors, and fields as indicating required dependencies.


Solution

  • If you place @Autowired annotation above other annotation declaration, the new annotation will have the same effect as @Autowired annotation. For example, in your case you can use @MyAnnotation above constructor, field, setter method or config method as to be autowired by Spring's dependency injection facilities.

    Moreover, you may discover, that @Controller annotation in spring framework declared as @Component. As result, classes that marked as @Controller also created as container beans.