DEV Community

kaede
kaede

Posted on • Edited on

1

Kotlin 基礎 Part 7 -- DI ( Dependency Injection ) コンテナへの登録 / 使用

参考

https://www.amazon.co.jp/gp/product/B091PGXHJY/ref=ppx_yo_dt_b_search_asin_title?ie=UTF8&psc=1

Kotlin サーバーサイドプログラミング実践開発

第4章 3 Springboot の DI を使用する

から。


DI とは

書籍によると、クラスで使用するオブジェクトの生成の自動化とある。

オブジェクト生成の自動化はインスタンス作成の自動化だ。

ここでの依存性注入は、自動で(初期読み込み時に)他のクラスのインスタンスを作ってあるクラスで使えるようにする仕組みだと解釈した。

https://www.w2solution.co.jp/tech/2021/10/06/eg_ns_rs_izonseinotyunyu/

この記事によると、オブジェクト(実装)の注入という。


@Component / @Named

どちらも DI コンテナに登録するもの。

DI コンテナとは、Spring App の起動時に読み込まれて固定される
React のグローバルステートのようなものだと解釈する。

https://qiita.com/asksaito/items/2c854065e5803463ebfd#コンポーネントスキャンの対象

この記事によると、Component も Named も機能は同じで
Spring のものか Java のライブラリのものかでしか無いようだ。


@Autowired @Inject

https://dawaan.com/autowired-vs-inject/

これらは DI コンテナから持ってきてそのクラス内部で使えるようにするもの。

上記と同様に Spring か Java のものかで、機能は同じ。

Mockk では InjectMocks を使って偽物としてインスタンス作成できる。

Top comments (0)

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay