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