---
title: SpringでDIを使うための最小サンプル
tags: []
categories: ["Programming", "Java", "org", "springframework"]
date: 2021-08-21T12:37:49Z
updated: 2022-03-17T17:35:10Z
---

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

### pom.xml

```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もついてきますが)

### コンポーネント作成

```java
package sample;

import org.springframework.stereotype.Component;

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

### Injectionする

コンポーネントを使う側

```java
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
