LoginSignup
191

More than 5 years have passed since last update.

SpringのDIとAOPの簡潔な説明

Posted at

前提

  • 本記事は「Spring3 入門」(通称:緑本)を参考にしました
  • Spring:Java言語のフレームワーク
  • Springの肝はDIとAOP

【DI】(Dependency Injection)

〜概要〜

日本語訳すると「依存性の注入」です。
SpringのDIコンテナの利点は大きく2つあります。それは、

  • クラスからnew演算子を消せる
  • インスタンス化を1回で済ませられる(Singleton)

です。

〜実装〜

実現する方法は2通りあります。

  • アノテーションを使う
  • Bean定義ファイルを使う

です。

アノテーションベースの方のみ説明書きます。

インスタンス変数(注入先の変数)の前に@Autowiredをつけると、@Componentアノテーションのついたクラスの中から該当するものを探し、newしてインスタンスを突っ込んでくれます!

▼(実装例)

ProductController.java
パッケージ名やimport文は省略
@Controller
public class ProductController {
    @Autowired
    private ProductService productService;

    メソッドなど
}
ProductService.java
@Service
public class ProductService {
    
}
  • @Componentアノテーションは、そのまま使うことはほとんどなく、レイヤに応じて@Controller or @Service or @Repositoryを使います。
  • productServiceというインスタンスには、@Component(Controller, Service, Repository)が付いているクラスの中からProductServiceクラスを探し出し、newしてインスタンスを突っ込んでくれます。

【AOP】(Aspect Oriented Programming)

〜概要〜

日本語訳すると「アスペクト指向プログラミング」です。
これは、オブジェクト指向に代わるものではなく、併用されるものです。

クラスには「本質的な処理」のみ記述し、「本質的ではない余計な処理(共通化出来る処理)」をアスペクトに記述します。
アスペクトには

  • Advice(振る舞い)
  • Pointcut(振る舞いを適用する条件)

があります。
Pointcut(条件)を満たすメソッドに対し、Advice(共通処理)を走らせることで、各クラスには本質的な処理だけを記述することが可能となるわけです。

〜実装〜

アスペクトを記述するクラスには@Aspectアノテーションを付けます。
アスペクトの条件と処理を書くメソッドには@Aroundなどのアノテーションを付けます。
@Before@After@Around@AfterThrowingがあるが、全て@Aroundのみで表現可能です)

▼(実装例)

ControllerAspect.java
@Aspect
public class ControllerAspect {
    @Around("execution(* findProduct(**))")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        前処理
        Object obj = point.proceed();
        後処理
        return obj;
    }
}
ProductController.java
@Controller
public class ProductController {
    @Autowired
    private ProductService productService;

    public Product findProduct() {
        処理
    }
}
  • @Around("execution(* findProduct(**))")のexecutionの中のカッコに、アスペクト処理を走らせる条件(Pointcut)を記述します。
  • @Aroundアノテーションを付けたメソッドには、
    • 「ProceedingJoinPoint」クラスの引数を必ず入れる
    • 必ずproceedメソッドを記述する
  • proceedメソッドを実行した時に、AOPの対象となっているメソッドが呼び出されます。

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
191