6

Possible Duplicate:
How to run an arbitrary startup function in a ring project?

I am using the clojure ring middleware, with compojure, to build a simple api. I deploy the app often as a war.

This works great, but I am looking at ways to have one off initialisation code run when the app starts. When I run "lein ring server" it runs just fine - however, when deployed as a war it seems to only run when the first request hits the server (i.e. lazy). Is there a way to make it not be lazy (without using AOT) - or is there a better way to hook into ring middleware lifecycle?

1

2 Answers 2

2

I think you are looking for :init param in the lein-ring plugin. Copied from https://github.com/weavejester/lein-ring:

:init - A function to be called once before your handler starts. It should take no 
arguments. If you've compiled your Ring application into a war-file, this function will 
be called when your handler servlet is first initialized.
2
  • that works when running "lein ring server" and is handy for that, however when deployed as a war, that function isn't called at all. Jun 21, 2012 at 4:55
  • 1
    The trick was that the :init function itself should not be in the project.clj Jan 14, 2013 at 21:30
1

A ServletContextListener implementation would serve your needs. If you don't feel like implementing one yourself with :gen-class, you can use the servlet utilities at the ring-java-servlet project.

To do so, create a file with the functions you wish called during startup and/or shutdown:

(ns my.project.init
  (:require [org.lpetit.ring.servlet.util :as util]))

(defn on-startup [context]
  (do-stuff (util/context-params context)))

(defn on-shutdown [context]
  (do-other-stuff (util/context-params context)))

Then hook this into your webapp via the following web.xml settings:

<context-param>
    <param-name>context-init</param-name>
    <param-value>my.project.init/on-startup</param-value>
</context-param>
<context-param>
    <param-name>context-destroy</param-name>
    <param-value>my.project.init/on-shutdown</param-value>
</context-param>
<listener>
    <listener-class>org.lpetit.ring.servlet.RingServletContextListener</listener-class>
</listener>

Not the answer you're looking for? Browse other questions tagged or ask your own question.