groovlet + springでちょっと試した。 2007/08/28

groovletがすごくいい感じなので、groovletでしばらく何かつくってみようかと考えていて、springと一緒に使えないかなと考えた。

どういったことを希望しているかというと、
xxx.groovletで呼ばれると、DIで必要なオブジェクトのインスタンスをgroovyに渡してくれるイメージです。

HttpServletResponseならresponse
HttpServletRequestならrequest
って感じで、groovletからは何も考えず使えます。

で、この仕組みはもちろん、GroovyServletが提供してくれています。で、このGroovyServletがgroovyスクリプトを初期化して、ServletBindingなるものを作成します。このServletBindingでresponse,requestとかをgroovletに渡してくれるための処理を行ってくれているようです。

そんな感じで、beans.xmlに定義したbeanをgroovletですぐに使えたら(setter injectionされて)いいなぁとか考えているのですが、調査中です。

で、groovletでspringを利用できるだけでもいいかなぁということで試してみました。

実験手順は、
(1)web.xmlに、リスナーを登録します。

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>


springを使うときのお決まりのようです。

(2)web.xmlに、context-paramを設定
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
WEB-INF/g.xml
</param-value>
</context-param>


この設定で,applicationContext.xml(beans.xml)のファイルパスを設定するってことですね。
g.xmlというの想定しています。下記のような内容にしてみました。groovyをbeanとして扱っています。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:lang="http://www.springframework.org/schema/lang"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-2.0.xsd">
<lang:groovy id="calc" script-source="classpath:calc.groovy"/>
</beans>


(3)groovletで使用します。
ちょっとまどろっこしい感じがします。
import org.springframework.web.context.WebApplicationContext

def ctx = context.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
def calc = ctx.getBean("calc");
calc.p()


ctx.getBeanだけすませたいですが...

springのコンテナを利用して、groovletを生成するのがいいのかなぁと考えています。
おいおい考えていきたいです。

: