user3369592 user3369592 - 4 months ago 107
Java Question

best way to create a global variable in Spring MVC

All of my controllers (requestMapping url) start with the same variable.

myController/blablabal


I am thinking about creating a global variable to replace "myController" so in the future if I change the URL name, I only need to change at one place.
The way I am currently doing this is to create a bean.
My bean config file:

<bean id="controllerURL" class="java.lang.String">
<constructor-arg type="String" value="tt"/>
</bean>


Then in my controller:

@RequestMapping(value ="/${controllerURL}/qrcode/blablbal", method = RequestMethod.GET)


However, it seems that I can not access this variable
controllerURL
correctly. Am I missing anything here? Or do we have a better way to create a global variable in Spring MVC?

Answer

Create a constant and use it. The compiler will merge the constant and the remaining url at compile-time.

public class MyConstants {
    public static final String PATH_PREFIX = "/myController/blablabal";
}
import MyConstants.PATH_PREFIX;

@Controller
public class MyController {
    @RequestMapping(path = PATH_PREFIX + "/qrcode/blablbal", method = RequestMethod.GET)
    // method here
}