Spring @Scheduled job - 获取基本应用程序路径

时间:2013-05-28 14:07:28

标签: spring servlets spring-mvc

我有一个Spring MVC应用程序,在其中我使用注释为@Scheduled的方法的类运行定期作业

在这种方法中,我希望根据这是我的本地系统还是生产系统来获取基本应用程序路径,即http://localhost:8080/http://www.mywebsite.com/

我该怎么做?我无法访问HttpServletRequest,因为它不是Controller类。

任何提示都将不胜感激

3 个答案:

答案 0 :(得分:4)

在我看来,在属性文件中使用配置文件和存储属性(如基本应用程序路径)是个好主意 - 其中每个环境都有自己的属性文件:config_dev.properties,config_production.properties

一旦他们在那里,您可以使用环境(在SpringSource blog上描述)将它们加载到类似工作的类中。

如何配置Tomcat和Spring以使用配置文件:Spring 3.1 profiles and Tomcat configuration

答案 1 :(得分:1)

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

运行应用程序服务器(或容器)时。这可以通过put,

来完成
JAVA_OPTS="$JAVA_OPTS -Dconfig.file.path=/path/to/myconfiguration.properties" 

在脚本的开头(大致),在运行应用程序服务器时使用。

  • 对于tomcat catalina.sh
  • 对于Jboss AS run.sh
  • 对于weblogic,setDomainEnv.sh

执行此操作后启动服务器并部署应用程序。最后,您的@Scheduled方法应该知道它需要的信息。由于属性文件在应用程序之外,您可以根据需要更改属性的值,而无需重建应用程序或甚至不会打扰它!

答案 2 :(得分:1)

只需在web.xml中添加此代码

即可
    <context-param>
    <param-name>webAppRootKey</param-name>
    <param-value>my.root.path</param-value>
</context-param>

并将您的代码用作系统属性