Jetty - 设置系统属性

Bos*_*one 17 configuration jetty system-properties

我在Jetty上运行webapp.应用程序的配置来自运行Jetty的同一服务器上的文件.在应用程序内部,我依靠系统属性来获取文件的路径,以便我可以解析它.例如

final String loc = System.getProperty(FACTORY);
Run Code Online (Sandbox Code Playgroud)

现在我可以使用D开关启动jetty以$FACTORY在命令行上提供但是如果可以的话我宁愿把它放在jetty.xml中.我知道有<SystemProperty />标签,但似乎只提供<Set/>标签已存在的系统值.有人可以举例说明如何实现这一目标吗?(如果可以实现)

tho*_*dge 22

为了记录在案,如果你真的需要通过系统属性来做到这一点(我一样),你可以做到这一点追加例如-Drun.mode =分期到系统属性:

<Call class="java.lang.System" name="setProperties">
  <Arg>
    <New class="java.util.Properties">
      <Call name="putAll">
        <Arg><Call class="java.lang.System" name="getProperties"/></Arg>
      </Call>
      <Call name="setProperty">
        <Arg>run.mode</Arg>
        <Arg>staging</Arg>
      </Call>
    </New>
  </Arg>
</Call>
Run Code Online (Sandbox Code Playgroud)

...是的你可以通过这个来编程你的应用程序;-)

  • 我添加了一个更紧凑的版本:`<Call class ="java.lang.System"name ="setProperty"> <Arg> run.mode </ Arg> <Arg> staging </ Arg> </ Call> (16认同)

小智 7

如果您通过Java API启动Jetty以进行测试或"嵌入式"应用程序,则以下示例显示在启动WebAppContext之前实际设置Java System属性.

    private void startJetty() {
    try {
        long startTime = System.currentTimeMillis();

        server = new Server();
        setUpSystemProperties(server);

        Connector connector = new SelectChannelConnector();
        connector.setPort(port);
        server.addConnector(connector);

        WebAppContext webAppContext = new WebAppContext();
        webAppContext.setWar("src/main/webapp");
        server.setHandler(webAppContext);

        server.start();
    }
    catch (Exception e) {
        throw new RuntimeException("Failed to set-up web server fixture", e);
    }
}

private void setUpSystemProperties(Server jettyServer) {
    final Properties systemProperties = new Properties();
    // set your system properties...
    systemProperties.setProperty("yourProperty", "yourValue");
    jettyServer.addLifeCycleListener(new SystemPropertiesLifeCycleListener(systemProperties));
}

private class SystemPropertiesLifeCycleListener extends AbstractLifeCycleListener {
    private Properties toSet;

    public SystemPropertiesLifeCycleListener(Properties toSet) {
        this.toSet = toSet;
    }

    @Override
    public void lifeCycleStarting(LifeCycle anyLifeCycle) {
        // add to (don't replace) System.getProperties()
        System.getProperties().putAll(toSet);
    }
}
Run Code Online (Sandbox Code Playgroud)

与大多数这些答案不同,我不会告诉你这与JNDI或其他你没有提出过的技术相比是否"合适".


van*_*nje 2

要配置 Web 应用程序,最好避免系统属性并使用 JNDI。

最近我发布了一个关于如何使用 Jetty 实现这一目标的示例。

  • 谢谢,但我仍然想知道是否可以完成以及如何完成。坦率地说,如果它是从 jetty.xml 设置的,而不是在系统本身中设置的,我不明白为什么它不好 (3认同)
  • 好处是便携性。如果您要将 Web 应用程序部署到另一个容器中,那么您可以确定有一种方法可以设置 JNDI 参数。据我所知 jetty.xml 中的“SystemProperty”标签仅用于读取系统属性。这是 Jetty 语法参考:http://docs.codehaus.org/display/JETTY/Syntax+Reference#SyntaxReference-SystemProperty (2认同)