Springに関して、本当の意味でのHello Worldはこれぐらいなのではないかと思う。
JDKとmavenだけに依存している。
(mavenを使わない方法も試みたが、むしろ複雑化して理解を損ねそうなのでやめた。)
ファイル一覧
./src/main/java/HelloWorld.java
./src/main/resources/applicationContext.xml
./pom.xml
各ファイルの内容
HelloWorld.java
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class HelloWorld {
public static void main(String[] args) {
new ClassPathXmlApplicationContext("applicationContext.xml").close();
}
}
applicationContext.xml
<?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:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<bean id="str1" class="java.lang.String">
<constructor-arg value="Hello World!"/>
</bean>
<util:constant id="systemOut" static-field="java.lang.System.out"/>
<bean id="invokingBean" class="org.springframework.beans.factory.config.MethodInvokingBean">
<property name="targetObject" ref="systemOut"/>
<property name="targetMethod" value="println"/>
<property name="arguments" ref="str1"/>
</bean>
</beans>
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>helloworld</groupId>
<artifactId>helloworld</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.6</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>11</source>
<target>11</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
動かし方と結果
% mvn compile exec:java -Dexec.mainClass=HelloWorld
(中略)
Hello World!
(中略)
解説
同じような処理をjava単体でハードコーディングすると以下のような形になる。
applicationContext.xmlと見比べてほしい。
public class HelloWorld {
public static void main(String[] args) {
String str1 = new String("Hello World!");
java.io.PrintStream systemOut = System.out;
systemOut.println(str1);
}
}
このコードを見てもまわりくどいし、Springを使うとさらにまわりくどいように見えるだろうが、アプリケーションの規模がある程度大きくなるとSpring Frameworkで組み上げることのメリットが勝ってくる。全体の見通しのよさや再利用性の高さを強く感じられるようになってくるだろう。
余談
10年ぶりぐらいにSpringを使おうと思い、とりあえずHello Worldを検索してみた。だが、なぜかどの例も「Eclipse」云々から始まっていたり「Web」だったり「getBean」していたり・・・。
「ちがーう!俺はEclipseを使ってないし、今作りたいのはバッチだし、getBeanを前提にしていたら『コンポーネントがSpringフレームワークに依存』しちゃうじゃないか!」
となったので、「俺の考えるHello World」を作ってこの記事を書きました。
以上