Rob Winch opened SPR-10760 and commented

When using @Autowire, custom @Value annotations can be created to help with reuse of annotations. For example, I might have:

@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Value("#{myUser}")
public @interface MyUser {

}

This would ensure the bean by name myUser is resolved for the following:


@Autowired
public void setMyUser(@MyUser String myUser) {
   ...
}

The code for meta @Value annotations can be found at QualifierAnnotationAutowireCandidateResolver#findValue in the second for loop.

It would be nice if ExpressionValueMethodArgumentResolver also supported such use cases. One concrete example of how users could use this is with Spring Security. For example, many users create a custom object that is placed in the Spring Security's Authentication. The Authentication is available on HttpServletRequest#getUserPrincipal(). This means the Authentication can be resolved using the ServletRequestMethodArgumentResolver. However, users should not be tied to the Spring Security APIs. One way to get around this is using @Value and relying on the ExpressionValueMethodArgumentResolver to resolve their custom class that is placed in the Authentication#getPrincipal() as shown below:

public String useCustomUser(@Value("#{request.userPrincipal.principal}") CustomUser custom) {
    ...
}

It would be nice if the following would work too:

@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Value("#{request.userPrincipal.principal}")
public @interface MyUser {

}

Controller method example:


public String useCustomUser(@MyUser CustomUser custom) {
    ...
}

Other HandlerMethodArgumentResolver that use annotations should also support meta annotations. For example: ModelAttributeMethodProcessor and it subclasses


2 votes, 2 watchers

Comment From: spring-projects-issues

Bulk closing outdated, unresolved issues. Please, reopen if still relevant.

Comment From: wingsofovnia

Can this be re-opened? Still no way to create a meta annotation for @Value

Comment From: sbrannen

@wingsofovnia, this is effectively a duplicate of #21829.

So, I'll add a note about @Value to the deliverables for that issue.