fastcampus-eatgo icon indicating copy to clipboard operation
fastcampus-eatgo copied to clipboard

10강 실습관련 질문

Open JE-Choi opened this issue 5 years ago • 1 comments

10강 실습 코드를 그래로 입력했을때, 아래와 같은 오류가 발생했습니다.

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'restaurantController': Unsatisfied dependency expressed through field 'r_repository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.springproject.eatgo.domain.RestaurantRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

코드는 아래와 같습니다. 제대로 입력한 것 같은데.. 뭐가 문제인 걸까요?

계속 오류에 대해서 찾아보니 @RestController @ComponentScan(basePackages = {"com.springproject.eatgo.domain"}) // 스캔할 패키지를 정의 public class RestaurantController {

처럼 RestaurantController 클래스 위에 "@ComponentScan"로 스캔한 패키지를 정의했더니, 오류가 해결되었습니다.

★ 최종 질문 : 그렇다면... @Autowired를 사용할 때는 "@ComponentScan" 를 필수로 추가해야 하는 것인가요? 추가하지 않도록, 환경설정으로 처리할 수 있는지 궁금합니다. 수업에서 언급되지 않은 부분이라 추가 질문 남깁니다.★

감사합니다. =====================*========================= <RestaurantRepository.java> package com.springproject.eatgo.domain;

import org.springframework.stereotype.Component;

import java.util.ArrayList; import java.util.List;

@Component public class RestaurantRepository { private List<Restaurant> restaurants = new ArrayList<>();

// 생성자
public RestaurantRepository(){
    restaurants.add( new Restaurant(1004L,"Bob zip", "Seoul"));
    restaurants.add( new Restaurant(2020L,"Cyber Food", "Seoul"));
}

public List<Restaurant> findAll() {
    return restaurants;
}

public Restaurant findById(Long id) {
    return restaurants.stream()
            .filter(r -> r.getId().equals(id))
            .findFirst()
            .orElse(null);
}

}

======================*======================== <RestaurantController.java> package com.springproject.eatgo.interfaces; import org.springframework.beans.factory.annotation.Autowired; import com.springproject.eatgo.domain.Restaurant; import com.springproject.eatgo.domain.RestaurantRepository; import org.springframework.context.annotation.ComponentScan; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import java.util.List;

@RestController public class RestaurantController { @Autowired private RestaurantRepository repository;

@GetMapping("/restaurants")
public List<Restaurant> list(){
    List<Restaurant> restaurants = repository.findAll();
    return restaurants;
}

@GetMapping("/restaurants/{id}")
public Restaurant detail(@PathVariable("id") Long id){
    Restaurant restaurant = repository.findById(id);
    return restaurant;
}

}

JE-Choi avatar Jan 10 '20 20:01 JE-Choi

완전히 동일하게 하셨다면 @ComponentScan은 불필요합니다. @SpringBootApplication이 이미 그걸 포함하고 있기 때문이죠. 이럴 때 어디가 다른지 주의 깊게 확인해 보시면 강의에서 설명한 것보다 더 많은 걸 배울 수 있습니다.

ahastudio avatar Mar 11 '20 11:03 ahastudio