【问题标题】:Spring @Scheduled job - Get base application pathSpring @Scheduled job - 获取基本应用程序路径
【发布时间】:2013-05-28 14:07:28
【问题描述】:
我有一个 Spring MVC 应用程序,在其中我正在使用一个带有注释为 @Scheduled 的类的类运行定期作业
在这种方法中,我想根据这是我的本地系统还是生产系统来获取基本应用程序路径,即http://localhost:8080/ 或http://www.mywebsite.com/。
我该怎么做?我无权访问 HttpServletRequest,因为这不是 Controller 类。
任何提示将不胜感激
【问题讨论】:
标签:
spring
servlets
spring-mvc
【解决方案2】:
在您的应用程序中添加一个myconfiguration.properties,让应用程序知道它是在本地运行还是在生产环境中运行。然后在您的方法中注释为@Scheduled 只需读取Property 文件。
String configPath = System.getProperty("config.file.path");
File file = new File(configPath);
FileInputStream fileInput = new FileInputStream(file);
Properties properties = new Properties();
properties.load(fileInput);
并提供agrument,
-Dconfig.file.path=/path/to/myconfiguration.properties
在运行应用服务器(或容器)时。这可以通过放置来完成,
JAVA_OPTS="$JAVA_OPTS -Dconfig.file.path=/path/to/myconfiguration.properties"
在脚本的开头(大致),在运行应用程序服务器时使用。
- 对于 Tomcat,其
catalina.sh
- 对于 Jboss AS,其
run.sh
- 对于 weblogic,其
setDomainEnv.sh
然后启动您的服务器并部署您的应用程序。最后,您的@Scheduled 方法应该知道它需要的信息。由于属性文件在应用程序之外,您可以在需要时更改属性的值,而无需重新构建应用程序,甚至不会干扰它!
【解决方案3】:
只需将此代码添加到您的 web.xml 中
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>my.root.path</param-value>
</context-param>
并将您的代码用作系统属性