Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using @Value annotation with static final variable in Spring Framework

I want to make the Request Mappings in my Spring application dynamic. So that my url can not be understandable. And I can show anything meaningless to the user and still mapping purpose will be resolved.

For that I am storing the dynamic part of the URL in properties file. And want to use that in the @RequestMapping annotation. And the same thing will be done on the client side in JSP. I will read the value from the property file and then create the href.

I am using @Value annotation to read the property file values.

There is one class that holds all such values in final static variables.

public class UrlMappingAbstraction {
    public static final @Value("#{urlAbstractionProperties['url.message']?:'message'}") String MESSAGE = "";
}

And I am extending this class in my controller and using the static final field in the @RequestMapping annotation like below.

@RequestMapping(value="/"+MESSAGE+"/{id}", method=RequestMethod.GET)

And in jsp also I am reading the value from property file using <spring:message/> and generating the url in href.

The problem is jsp able to create the correct url based on the property file value but in the @RequestMapping annotation my value is not getting replaced.

Can anybody tell me the exact problem? I know that we can not change the value of static final variable after its initialized. Then what's the use of @Value annotation.

If this can be done another way then you can also show me it.

Thanks in advance.

like image 651
Japan Trivedi Avatar asked Jan 21 '13 12:01

Japan Trivedi


1 Answers

Annotations are static by their nature, therefore you cannot do it this way.

@Value cannot be used on static fields, but it doesn't matter here - the real problem is that there is no way to use values other than compile time constants as attributes of annotations.

You can use one of the following alternatives:

  • Add a URL rewrite filter (such as this or this) and configure it to perform the necessary conversion.

    This approach looks more elegant due to clear separation of responsibilities - controllers are responsible for doing their jobs, rewrite filter is responsible for obfuscation of URLs.

  • Intercept creation of controller mappings by overriding RequestMappingHandlerMapping. getMappingForMethod() and change their URL patterns at this step (not tested)

like image 70
axtavt Avatar answered Oct 29 '22 16:10

axtavt