我有一个 Spring MVC 应用程序,在其中我正在使用一个带有注释为方法的类运行定期作业@Scheduled
在这种方法中,我想获取基本应用程序路径,即http://localhost:8080/
或者http://www.mywebsite.com/
基于这是我的本地系统还是生产系统。
我怎样才能做到这一点?我无权访问 HttpServletRequest,因为这不是 Controller 类。
任何提示将不胜感激
我有一个 Spring MVC 应用程序,在其中我正在使用一个带有注释为方法的类运行定期作业@Scheduled
在这种方法中,我想获取基本应用程序路径,即http://localhost:8080/
或者http://www.mywebsite.com/
基于这是我的本地系统还是生产系统。
我怎样才能做到这一点?我无权访问 HttpServletRequest,因为这不是 Controller 类。
任何提示将不胜感激
在我看来,使用配置文件并在属性文件中存储诸如基本应用程序路径之类的属性是一个好主意 - 每个环境都有自己的属性文件:config_dev.properties、config_production.properties
一旦它们在那里,您就可以使用 Environment(在SpringSource 博客中描述)将它们加载到类似作业的类中。
如何配置 Tomcat 和 Spring 以使用配置文件:Spring 3.1 配置文件和 Tomcat 配置
Put a myconfiguration.properties
out of your application, to let the application know that whether its running locally or in production. And then in your method annotated as @Scheduled
just read the Property
file.
String configPath = System.getProperty("config.file.path");
File file = new File(configPath);
FileInputStream fileInput = new FileInputStream(file);
Properties properties = new Properties();
properties.load(fileInput);
And provide the agrument,
-Dconfig.file.path=/path/to/myconfiguration.properties
when running your application server (or container). This can be done by putting,
JAVA_OPTS="$JAVA_OPTS -Dconfig.file.path=/path/to/myconfiguration.properties"
at the beginning (roughly) of the script, which is used while running your application server.
catalina.sh
run.sh
setDomainEnv.sh
And After doing that start your server and deploy your application. Finally, your @Scheduled
method should know the information it needs. As the property file is outside of the application, you can change the value of the property when you want without rebuilding the application or without even disturbing it!
只需将此代码添加到您的 web.xml
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>my.root.path</param-value>
</context-param>
并将其用作您的代码作为系统属性