0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Spring boot メモ書き(2)

Last updated at Posted at 2019-07-28

目的

業務効率化

DI(Dependency injection)コンテナとは

ひとことでいうと、「プログラムではなく外部よりインスタンスを注入すること」 = 「依存性の注入」として訳されます。

new演算子を使ってプログラム内でインスタンスを作るのではなく、外部機能でインスタンスを作成して使用することができる

SpringBootではDI(依存性注入)を用いた設計が採用されており、コードの依存性を少なくすることができます。

クラスのインスタンスであるBeanは、DIコンテナに保存されます。

SpringBootのクラス間の呼び出し等は、DIコンテナに登録されたBeanを取得することで実行されます。

標準的なBeanの登録方法は、以下方法があります。

  1. @Beanをメソッドに付与する。メソッドの返り値に指定したクラスのシングルトンが、DIコンテナに登録される
  2. Bean登録したいクラスに、@Componentをクラスに付与する。そのクラスのシングルトンがDIコンテナに登録される
  3. API宣言である@RestController や 環境クラス宣言である@Configurationt等、付与するだけでそのクラスのBean登録がされる。

SpringBootの起動時に、@ComponentScanで指定したパッケージ以下をDIコンテナの読み込み対象にします。

@SpringBootApplication
/* demo.serviceとdemo.domain以下のうち、@componentやDI登録用アノテーションが
付与されているクラス/メソッドをDIコンテナにBean登録する。 */
@ComponentScan(
		scopedProxy = ScopedProxyMode.TARGET_CLASS,
		basePackages = {"demo.service","demo.domain"}
		)
public class SBDataBaseDemoApplication {
 
	public static void main(String[] args) {
		SpringApplication.run(SBDataBaseDemoApplication.class, args);
	}
}

DI対象となる主なアノテーション

@Controller コントローラー層のクラスに使用する。
@RestController WebAPIのコントローラー層のクラスに使用する。@Controller@ResponseBodyを組み合わせたものです。
@Service サービス層のクラスに使用する。主にビジネスロジックを実行するクラスに使用する。
@Repository データ層のクラスに使用する。主にDBアクセスするクラスに使用する。
@Component 上記の他にDI対象とするクラスに使用する。

image.png

参考

Spring 主要ポイント

https://atuweb.net/201509_spring_framework_good_points/

Spring Bootで作るRESTful Web Service

https://www.slideshare.net/WataruOhno/spring-fest-2018-spring-bootrestful-web-service
https://terasolunaorg.github.io/guideline/5.0.1.RELEASE/ja/ArchitectureInDetail/REST.html

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?