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



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

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

我该怎么做?我没有访问HttpServletRequest,因为这不是一个控制器类。

如有任何提示,不胜感激

在我看来,使用概要文件并在属性文件中存储像基本应用程序路径这样的属性是一个好主意——每个环境都有自己的属性文件:config_dev。属性,config_production.properties

一旦它们存在,你就可以使用Environment(在SpringSource博客上描述)将它们加载到类似作业的类中。

如何配置Tomcat和Spring使用配置文件:Spring 3.1配置文件和Tomcat配置

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);

并提供协议,

-Dconfig.file.path=/path/to/myconfiguration.properties

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

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

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

  • tomcat的catalina.sh
  • Jboss的run.sh
  • weblogic的setDomainEnv.sh

然后启动服务器并部署应用程序。最后,您的@Scheduled方法应该知道它需要的信息。由于属性文件位于应用程序之外,您可以在需要时更改属性的值,而无需重新构建应用程序,甚至不会干扰应用程序!

在web.xml中添加这段代码

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

并将其用作代码中的系统属性

最新更新