DEV Community

Willian Ferreira Moya
Willian Ferreira Moya

Posted on • Originally published at springmasteryhub.com

1

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!

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →