Spring初心者向けのDI事始め
以前、ありもののSpringを使ったアプリケーションを触った事はあったのですが、自分で1から導入して使っていくというのはやった事がなかったので、いろいろ試しています。
以下は「Hello World!」だけの薄い内容ですが、むしろその方がとっかかりでひっかかってる方には助かったりするかもという事でメモを晒しておきます。
DIとかSpringとかの説明はググれば優れたものがたくさんありますので、そちらをご覧下さい。私は、DIについてはWEB+DB PRESSでの羽生さんの一連の解説記事をかなり参考にして学びました。
以下はEclipse上での作業です。
まず必要なライブラリは以下です。
- spring.jar
- log4j-1.2.15.jar
- commons-logging.jar
これらをSpringSample/libの下においてbuild pathに追加します。
log4j.propertiesはSpringSample/src配下など適当な場所に以下のような感じで。
log4j.rootCategory=, A2 log4j.appender.A2=org.apache.log4j.RollingFileAppender log4j.appender.A2.MaxFileSize=1MB log4j.appender.A2.MaxBackupIndex=0 log4j.appender.A2.File=./spring_sample.log log4j.appender.A2.Append=false log4j.appender.A2.layout=org.apache.log4j.PatternLayout log4j.appender.A2.layout.ConversionPattern=%d{yyyy.MM.dd,HH:mm:ss,SSS},%F:%L,%p,%m%n
適当なpackage(例ではcx.ath.seratch)の下にMessageというInterfaceをつくります。
package cx.ath.seratch; public interface Message { public void say(); }
このInterfaceの実装クラスをつくります。
package cx.ath.seratch.impl; import cx.ath.seratch.Message; public class MessageImpl implements Message { private String message; public MessageImpl() {} public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public void say() { System.out.println(this.message + " World!"); } }
このMessage型のオブジェクトをDIするための設定ファイルであるapplicationContext.xml(ファイル名は任意)をSpringSample/srcなど適当な場所に置きます。
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="message" class="cx.ath.seratch.impl.MessageImpl"> <property name="message"> <value>Hello</value> </property> </bean> </beans>
これはSetter Injectionと呼ばれるDIの手法で、beanとなるクラスでsetterが用意されているプロパティをpropertyタグ内で記述することによって、Springフレームワークがcontainer生成時にそのsetterを使ってプロパティをsetしておいてくれます。
最後にSpringのDIコンテナを呼び出すMainのクラスをつくります。
package cx.ath.seratch; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); Message message = (Message) context.getBean("message"); message.say(); } }
ではこれをLinux/Unixサーバ上で実行してみましょう。
build.xmlを書いて実行可能なjarファイルを生成します。
<?xml version="1.0"?> <project name="SpringSample" default="all" basedir="."> <property name="build.dir" value="." /> <property name="src.dir" value="src" /> <property name="lib.dir" value="lib" /> <property name="dist.dir" value="classes" /> <property name="domain" value="cx.ath.seratch" /> <property name="main.class" value="${domain}.Main" /> <path id="project.classpath"> <fileset dir="lib"> <include name="*.jar" /> </fileset> </path> <target name="all" depends="init, compile, jar, clean" /> <target name="init"> <mkdir dir="${dist.dir}" /> </target> <target name="compile"> <copy todir="${dist.dir}"> <fileset dir="${src.dir}"> <include name="*.xml" /> <include name="*.properties" /> </fileset> </copy> <javac srcdir="${src.dir}" destdir="${dist.dir}" > <classpath refid="project.classpath" /> </javac> </target> <target name="jar"> <jar jarfile="spring_sample.jar" basedir="${dist.dir}"> <manifest> <attribute name="Class-Path" value=". commons-logging.jar spring.jar log4j-1.2.15.jar" /> <attribute name="Main-Class" value="${main.class}"/> </manifest> </jar> </target> <target name="clean"> <delete dir="${dist.dir}" /> </target> </project>
生成されたspring_sample.jarと依存関係のライブラリのjarをサーバに転送します。
- spring_sample.jar
- commons-logging.jar
- spring.jar
- log4j-1.2.15.jar
コマンドラインからspring_sample.jarをたたいてみます。
-bash-3.00$ java -jar spring_sample.jar Hello World! -bash-3.00$
このままでは開発に使えるものではありませんが、とりあえずこれでSpringを使ってDIするやり方の雛形はできたかと思います*1。あとはドキュメントを読みながらという感じです。
*1:かなり初歩ですが・・