study-note

Service / DI(依存性注入)

目次

基本構文

package com.example.demo.service;

import org.springframework.stereotype.Service;

@Service
public class GreetingService {

  public String getMessage(String name) {
    return "こんにちは、" + name + "さん!";
  }
}

ControllerでServiceを使う

package com.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.ui.Model;
import com.example.demo.service.GreetingService;

@Controller
public class GreetingController {

  private final GreetingService greetingService;

  // 依存性注入(コンストラクタによるDI)
  public GreetingController(GreetingService greetingService) {
    this.greetingService = greetingService;
  }

  @GetMapping("/service")
  public String greeting(Model model) {
    String message = greetingService.getMessage("ユーザー");
    model.addAttribute("msg", message);
    return "service";
  }
}

DI(依存性注入)とは

依存性注入方法の種類

  1. コンストラクタ注入:public Controller(Service s)
    • 最も推奨される
    • 不変
    • テストしやすい
  2. フィールド注入:@Autowired private Service s;
    • 簡単だが非推奨
    • テストしにくい
  3. Setter注入:@Autowired public void setService(Setvice s)
    • 状況によっては使用可

Beanの範囲


→ 次:Repository