Java & Spring/์คํ๋ง
[์๋ฐ][์คํ๋ง] DI, Dependency injection
Rainbow๐Coder
2023. 1. 1. 16:28
728x90
์๋ ํด๋์ค ์์ ํ๋๋ฅผ ๋ฃ์ด์ค ๋ new () ...์์ผ๋ก ์ธ์คํด์ค ์์ฑํ์ฌ ๋ฃ์ด์ค๋ค.
ํ์ง๋ง
@RestController
๋ฅผ ๋ถ์ฌ์ค ํด๋์ค๋ ์คํ๋ง์์ ํ๋์ ์ธ์คํด์ค๋ฅผ ๋ณด๊ดํ๊ณ ์๋ค.
๊ทธ๋์ Autowired ์ธ ๋๋ง๋ค ํด๋น ํ๋์ ๋์ ํด์ค๋ค.
@Autowired
private MarketService marketService;
//์ฐธ๊ณ ๋ก
marketService
๋ ์๋น์ค@Service๋ผ๋ ์ด๋ ธํ ์ด์ ๋ถ์ฌ์ค๋ค.
์๋น์ค ๋ถ์ธ ๊ฒ๋ค๋ง ์คํ๋ง ์ปจํ ์คํธ์ ์ธ์คํด์ค๋ค์ด ๋ค์ด๊ฐ๊ฒ ๋๋๋ฐ
์ด๋ฌํ ์ธ์คํด์ค๋ค์ '๋น'์ด๋ผ๊ณ ๋ถ๋ฅธ๋ค.
package com.bbokkie.coinner.controller;
import com.bbokkie.coinner.service.MarketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MarketController {
@Autowired
private MarketService marketService;
@GetMapping("/price")
public double getPrice(
@RequestParam String market, @RequestParam String coin
){
marketService.getPrice(market,coin);
return 123.456;
}
}
package com.bbokkie.coinner.service;
import org.springframework.stereotype.Service;
@Service
public class MarketService {
public double getPrice(
String market, String coin
){
return 123.444;
}
}

728x90