본문 바로가기

SpringBoot/스파르타 스프링 심화

[스파르타 스프링 심화] 01.16 스프링 IoC 컨테이너 사용하기

728x90
반응형

##스프링 IoC 컨테이너

: DI를 위해 스프링 프레임워크에서 객체들을 빈으로 저장해놓고 자동 객체 생성 해줌

 

-빈 (Bean): 스프링이 생성해주는 객체

-스프링 IoC 컨테이너: 빈을 모아둔 통

 

1. 주요 어노테이션

-@Configuration : 스프링 Ioc 컨테이너임을 나타냄

-@Bean : 스프링 컨테이너에 주입될 빈임을 나타냄

-@Autowired : DI를 받는 것을 나타냄

 

2.BeanConfiguration

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.sparta_spring.sparta_springcore_week01;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
@Configuration // 스프링 Ioc 컨테이너임을 선언
public class BeanConfiguration {
 
    @Bean // 스프링 Ioc 컨테이너에 빈 객체로 저장
    public ProductRepository productRepository() {
        String dbId = "sa";
        String dbPassword = "";
        String dbUrl = "jdbc:h2:mem:springcoredb";
        return new ProductRepository(dbId, dbPassword, dbUrl);
    }
 
    @Bean // 스프링 Ioc 컨테이너에 빈 객체로 저장
    @Autowired // DI를 받는것을 표시
    public ProductService productService(ProductRepository productRepository){
        return new ProductService(productRepository);
    }
}
 
cs

3.ProductController

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package com.sparta_spring.sparta_springcore_week01;
 
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
 
import java.sql.SQLException;
import java.util.List;
 
 
@RestController // JSON으로 데이터를 주고받음을 선언합니다.
public class ProductController {
    // 멤버 변수 선언
    private final ProductService productService;
    // 의존주입으로 ProductService 재활용
    // 생성자: ProductController() 가 생성될 때 호출됨
    @Autowired // DI 받는 것잇을 표시
    public ProductController(ProductService productService){
        this.productService = productService;
    }
 
 
    // 등록된 전체 상품 목록 조회
    @GetMapping("/api/products")
    public List<Product> getProducts() throws SQLException {
        List<Product> products = productService.getProducts();
        // 응답 보내기
        return products;
    }
 
    // 신규 상품 등록
    @PostMapping("/api/products")
    public Product createProduct(@RequestBody ProductRequestDto requestDto) throws SQLException {
        Product product = productService.createProduct(requestDto);
        // 응답 보내기
        return product;
    }
 
    // 설정 가격 변경
    @PutMapping("/api/products/{id}")
    public Long updateProduct(@PathVariable Long id, @RequestBody ProductMypriceRequestDto requestDto) throws SQLException {
        Product product = productService.updateProduct(id, requestDto);
        return product.getId();
    }
}
cs

 

4. ProductService

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.sparta_spring.sparta_springcore_week01;
 
import org.springframework.beans.factory.annotation.Autowired;
 
import java.sql.SQLException;
import java.util.List;
 
 
public class ProductService {
 
    private final ProductRepository productRepository;
    // DI의존주입 ProductRepository 재활용
    //생성자
    @Autowired // DI 받는것 표시
    public ProductService(ProductRepository productRepository){
        this.productRepository = productRepository;
    }
 
    public List<Product> getProducts() throws SQLException {
        return productRepository.getProducts();
    }
 
    public Product createProduct(ProductRequestDto requestDto) throws SQLException {
        // 요청받은 DTO 로 DB에 저장할 객체 만들기
        Product product = new Product(requestDto);
        productRepository.createProduct(product);
        return product;
    }
 
    public Product updateProduct(Long id, ProductMypriceRequestDto requestDto) throws SQLException {
        // 최저가 0 미만 예외처리
        if(requestDto.getMyprice() < 0){
            throw new IllegalAccessError("최저가는 0 이상입니다.");
        }
 
        Product product = productRepository.getProduct(id);
        if (product == null) {
            throw new NullPointerException("해당 아이디가 존재하지 않습니다.");
        }
        int myPrice = requestDto.getMyprice();
        productRepository.updateProductMyPrice(id, myPrice);
        return product;
    }
}
cs

5.ProductRepository

-멤버변수 생성자 추가

1
2
3
4
5
6
7
8
9
10
11
  // 멤버변수
    private String dbId; // db아이디
    private String dbPassword; // db 비번
    private String dbUrl; // db 주소
 
    // 생성자
    public ProductRepository(String dbId, String dbPassword, String dbUrl) {
        this.dbId = dbId;
        this.dbPassword = dbPassword;
        this.dbUrl = dbUrl;
    }
cs
반응형