WicketとSpringを悪魔合体させる その1
0. ではがったいさせるぞ
データアクセスがからむユニットテストをやるには、やはりDIの力を借りるのが手っ取り早い。
CDIでもいいんだけれど、今回はSpringを使ってみることにする。
アプローチとしては
- WicketをベースにSpringのDIを個別に組み込む
- Spring BootをベースにフロントをWicketにする
の二つがあるが、今回は前者にチャレンジしてみる。
1. 準備
何はなくともpom.xml
の依存設定だ。wicket-spring
を依存に追加する。
そのほか、SpringのDIをつかうので、Spring Contextとjavax.annotation-apiも加える。
<dependency>
<groupId>org.apache.wicket</groupId>
<artifactId>wicket-spring</artifactId>
<version>${wicket.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactid>spring-context</artifactId>
<version>5.1.10.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactid>javax.annotation-api</artifactId>
<version>1.3.2</version>
</dependency>
2. 各所の実装
話を簡単にするため、今回はView側にDIでねじ込まれた値を張るだけにしてみる。こんな感じ。
- HomePage.html
<!DOCTYPE html>
<html xmlns:wicket="http://wicket.apache.org" lang="ja">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<h1>
<span wicket:id="message">hello</span>
</h1>
<p>
java.version = <span wicket:id="versionCode">8</span> .
</p>
</body>
</html>
- HomePage.kt
class HomePage(parameters: PageParameters): WebPage(parameters) {
// Autowired ではなく org.apache.wicket.spring.injection.annot.SpringBean を使う
@SpringBean
private lateinit var enterpriseMessage: EnterpriseMessage
init {
add(Label("message", Model.of(enterpriseMessage.message)))
add(Label("versionCode", Model.of(enterpriseMessage.versionCode)))
}
}
エントリーポイントになるWebApplicationの継承クラスは、DIしたいパッケージにコンポーネントスキャンをかけてSpringの管理下に置く処理を書く。
class WicketApplication(): WebApplication {
override fun init() {
super.init()
val ctx = AnnotationConfigApplicationContext()
// コンポーネントスキャン対象を指定
ctx.scan("net.formula97.webapps.beans")
ctx.refresh()
// Wicket-Springの機能でSpringの管理下に置く
getComponentInstantiationListeners().add(SpringComponentInjector(this, ctx))
}
}
Spring管理下に置かれたクラスは、今回は定数クラスっぽい扱いにしてみた。
@ManagedBean
class EnterpriseMessage {
val message: String = "Welcome to the Spring-Integrated world!"
val versionCode: String = System.getProperty("java.version")
}
こうしてやることで、マネージドビーンをnewすることなく(そもそもKotlinだとインスタンスを作るのにnewというキーワードは使わないのだが)使うことができるようになる。
« Spring + Thymeleafで検索 + ページング + ソートを同時にやる件 | トップページ | WicketとSpringを悪魔合体させる その2 »
« Spring + Thymeleafで検索 + ページング + ソートを同時にやる件 | トップページ | WicketとSpringを悪魔合体させる その2 »
コメント