Spring boot core

정은하·2024년 1월 15일
post-thumbnail

직접 객체를 생성하는 대신 스프링이 객체를 생성 등 관리하라고 요청-> 스피링 빈으로 등록!

  1. @Component
  2. @Configuration+@Bean
    ->동록된 빈을 사용하게 주입해줘
    //필드 안에서 사용할 수 있는 스프링 컨테이너에 들어있는 빈 중에 알맞은 빈 찾아서 넣어주는 역할
    @Autowired

@Component

->@Service에 이미 포함

-ProductController

@Controller
@ResponseBody
public class ProductController {
    @Autowired
    private ProductService productService;
    //상품 조회(목적: 요청)
    @RequestMapping(value="", method = RequestMethod.GET)
    public String findProduct(){

        return productService.findProduct();

    }

}

-ProductService

@Service
public class ProductService {
    public String findProduct(){
        return "Notebook!!!";
    }
}

repository

-ProductRepository

@Repository
public class ProductRepository {
    //데이터베이스 생성-> 디비 저장소가 없는 경우 map을 이용해서 생성
    private Map<Integer,String> db=new HashMap<>();
    private int id=1;
    public String findProduct(){
        return "Notebook!!!!";
    }

}

-ProductService

@Service
public class ProductService {
    @Autowired
    private ProductRepository productRepository;
    public String findProduct(){
        return productRepository.findProduct();
    }
}

DI 방법

  1. 필드로 주입 받음
    -@Autowired
    -필드 마련
  2. Setter로 주입 받음
    -자주 사용하지는 않음
    -@Autowired
    -setter 메소드
  3. 생성자로 주입 받음
    -중요한 방식
    -@Autowired
    -생성자 마련

생성자로 주입 받는 방식

-ProductService

@Service
public class ProductService {
    //필드
    private ProductRepository productRepository;
    //생성자
    @Autowired
    ProductService(ProductRepository productRepository){
        this.productRepository=productRepository;
    }
    public String findProduct(){
        return productRepository.findProduct();
    }
}
profile
If you remain stagnant, you won't achieve anything

0개의 댓글