SpringでDIを使うための最小サンプル

すごく昔(Spring Bootもない時代)に書いた記事の最新版

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>org.example</groupId>
	<artifactId>minimal-spring-di</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<properties>
		<maven.compiler.source>11</maven.compiler.source>
		<maven.compiler.target>11</maven.compiler.target>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>5.3.17</version>
		</dependency>
	</dependencies>

</project>

DIを使うだけならspring-contextだけで十分(AOPもついてきますが)

コンポーネント作成

package sample;

import org.springframework.stereotype.Component;

@Component
public class GreetingService {
	public String hello(String message) {
		return "Hello " + message + "!";
	}
}

Injectionする

コンポーネントを使う側

package sample;

import org.springframework.stereotype.Component;

@Component
public class MyApp {
	private final GreetingService greetingService;

	public MyApp(GreetingService greetingService) {
		this.greetingService = greetingService;
	}

	public void run(String message) {
		System.out.println(this.greetingService.hello(message));
	}
}

コンストラクタインジェクションします。コンストラクタが一つの場合は@Autowiredつける必要もありません。

エントリポイント

package sample;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.GenericApplicationContext;

@Configuration
@ComponentScan
public class Main {
	public static void main(String[] args) {
		try (GenericApplicationContext applicationContext = new AnnotationConfigApplicationContext(Main.class)) {
			MyApp app = applicationContext.getBean(MyApp.class);
			app.run("Spring");
		}
	}
}

AnnotationConfigApplicationContextにコンポーネントスキャンを設定したJavaConfigクラス(ここではMain)を指定してDIコンテナ作成。 getBeanでDIコンテナに管理されたBeanを取得できます。タイプセーフです。

Mainクラスのmainメソッドを実行すれば次のログが出力されます。

Hello Spring!

オンラインで試す https://onecompiler.com/java/3xwdkvpcc