package com.example.demo.service;
import org.springframework.stereotype.Service;
@Service
public class GreetingService {
public String getMessage(String name) {
return "こんにちは、" + name + "さん!";
}
}
@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";
}
}
GreetingServiceのインスタンスを自動で作り、GreetingControllerに注入するnewを差し込むnewするpublic Controller(Service s)
@Autowired private Service s;
@Autowired public void setService(Setvice s)
@Conponent:汎用Bean@Service:ビジネスロジック層@Repository:データアクセス層@Controller:Web層(HTML返却、MVC用)@RestController:Web層(JSON返却、API用)@Configuration:設定クラス→ 次:Repository