DEV Community

Willian Ferreira Moya
Willian Ferreira Moya

Posted on • Originally published at springmasteryhub.com

How @AliasFor Simplifies Annotations usage in Spring

This annotation is an annotation that allows you to create an alias for an attribute in an annotation. These attributes have the same function. The idea is to avoid confusion when multiple attributes can be used for the same purpose

Maybe this is the first time you have seen it.

Spring uses this annotation in places like @Bean, @ComponentScan, @Scope, @RequestMapping, etc.

So it’s more used internally. And maybe you are already using its functionality and don’t even know.

Let’s take a look at how @RequestMapping is using this annotation:

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
@Reflective({ControllerMappingReflectiveProcessor.class})
public @interface RequestMapping {
    String name() default "";

    @AliasFor("path")
    String[] value() default {};

    @AliasFor("value")
    String[] path() default {};

    RequestMethod[] method() default {};

    String[] params() default {};

    String[] headers() default {};

    String[] consumes() default {};

    String[] produces() default {};
}

Enter fullscreen mode Exit fullscreen mode

The attributes path and value have the same purpose, they define the URL pattern for your request mappings.

The scenario below shows how the effect is the same and you can choose the alias you want.

@Controller
public class AlisForController {

    @RequestMapping(value = "/home", method = RequestMethod.GET)
    public String homePage() {
        return "home";
    }

    // Equivalent to the above using 'path'
    @RequestMapping(path = "/home", method = RequestMethod.GET)
    public String homePage2() {
        return "home";
    }
}

Enter fullscreen mode Exit fullscreen mode

Have you ever seen this before?

Have some dev defined the path and in another controller, you found that it’s using a value for the same purpose, and somehow everything works, now you know why it works.

Conclusion

So, pay attention to your project, have you found any places where this happened? Open the annotation’s code and see the @AliasFor there.

If you like this topic, make sure to follow me. In the following days, I’ll be explaining more about Spring annotations! Stay tuned!

Follow me!

Top comments (0)