Agile Web Development with Railsの例題と同じ問題をSpringを使って実装を試みたときの メモです。
もう一つの目的は、Spring-MVCプラグインがどの程度実際の問題解決に役立つかを検証することです。
mavenを使ってプロジェクトを生成します。
とします。ecliseでプロジェクトを管理できるようにeclipseプラグインも起動します。
mvn archetype:create \ -DgroupId=example.cart \ -DartifactId=cart \ -DarchetypeArtifactId=spring-mvc-archetype \ -DarchetypeGroupId=jp.co.pwv.spring-mvc-archetype \ -DarchetypeVersion=1.1.1 cd cart mvn eclipse:eclipse -DdownloadSources=true
データベースは、HsqlDBのサーバを使用するため、db.propertiesの内容を修正します。
db.url=jdbc:hsqldb:hsql://localhost
最後にeclipseでcartプロジェクトをimportし、CVSに登録します。
cartはセッションの中で管理しなければなりません。そのため、Spring2.0から導入されたsession scopeを使用します。
まずは、session scopeの使い方を確認します。
最初に以下のような簡単なクラスを定義します。
package example.cart.service; public class CartService { private Integer id; public CartService() { id = new Integer(1); } }
session scopeオブジェクトは、サーブレットではなく、applicationContext.xmlと同レベルで定義しないとbeanが見つからないとのエラーになります。
そこで、session-def.xmlにsession scopeをまとめて定義しました。
<?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:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"> <!-- a HTTP Session-scoped bean exposed as a proxy --> <bean id="cartService" class="example.cart.service.CartService" scope="session" /> </beans>
本当は、<aop:scoped-proxy />を使って自動的にsession scopeオブジェクトの再配置をしたかったのですが、何度もテストしましたがこの宣言を入れるとうまくオブジェクトがセットされません。
次にこのsession scopeオブジェクトを使用するメソッド(ここではlistメソッド)に
ApplicationContext co = WebApplicationContextUtils.getRequiredWebApplicationContext( request.getSession().getServletContext()); Object obj = co.getBean("cartService");
としてアプリケーション・コンテキストからcartServiceを取得します。
次に、デバッガでCartServiceのコンストラクタにブレークポイントをセットし、tomcatを起動します。
ブラウザーからlistのページにアクセスするとcartServiceオブジェクトのコンストラクタがコールされます。
ブラウザーを起動し直すと再度cartServiceオブジェクトのコンストラクタがコールされ、session毎に オブジェクトが生成されることが確認できます。