【问题标题】: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


    【解决方案1】:

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

    一旦它们在那里,您就可以使用 Environment(在 SpringSource blog 中描述)将它们加载到类似作业的类中。

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

    【讨论】:

      【解决方案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>
        

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-10-02
          • 2014-11-07
          • 1970-01-01
          • 2011-09-08
          • 1970-01-01
          • 2012-10-23
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多