java 在 Spring MVC 中创建全局变量的最佳方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38644536/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
best way to create a global variable in Spring MVC
提问by user3369592
All of my controllers (requestMapping url) start with the same variable.
我的所有控制器(requestMapping url)都以相同的变量开头。
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:
我正在考虑创建一个全局变量来替换“myController”,所以将来如果我更改 URL 名称,我只需要在一个地方更改。我目前这样做的方法是创建一个 bean。我的bean配置文件:
<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?
但是,我似乎无法controllerURL
正确访问此变量。我在这里错过了什么吗?或者我们有更好的方法在 Spring MVC 中创建全局变量吗?
回答by carlos_technogi
I would create a BaseController with the base URL
我会用基本 URL 创建一个 BaseController
import org.springframework.web.bind.annotation.RequestMapping;
@RequestMapping("/base")
public class BaseController {
}
and implement it
并实施它
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController extends BaseController{
@RequestMapping("/hello")
String hello(){
return "Hello";
}
}
回答by Andreas
Create a constantand use it. The compiler will merge the constant and the remaining url at compile-time.
创建一个常量并使用它。编译器将在编译时合并常量和剩余的 url。
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
}
回答by Sundararaj Govindasamy
You can create global variable using beanas below.
您可以使用 bean创建全局变量,如下所示。
1.In your bean declaration,
1.在你的bean声明中,
Use java.lang.String
insteadof String
in constructor type attribute.
使用java.lang.String
替代的String
在构造类型属性。
<bean id="controllerURL" class="java.lang.String">
<constructor-arg type="java.lang.String" value="tt"/>
</bean>
In your Controller,
@Autowired String controllerURL;
在您的控制器中,
@Autowired 字符串控制器URL;
and
和
@RequestMapping(value = controllerURL +"/qrcode/blablbal", method = RequestMethod.GET)