에러가 발생한 기존 코드
@Controller
public class DepartmentController {
@Autowired
@GetMapping("/list")
public String list(Model model) {
// Model 객체는 요청 처리 시 자동으로 주입되어야 하는데, @Autowired로 인해 빈 검색 대상이 되어 에러 발생
model.addAttribute("departments", departmentService.getAll());
return "departmentList";
}
}
controller에서 @Autowired 어노테이션을 선언만 하고 의존성을 주입하지 않은 상태에서 서버를 재시작한다면 아래의 에러가 발생한다.
'myDepartment': Unsatisfied dependency expressed through method 'list' parameter 0;
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean found for dependency [org.springframework.ui.Model]:
expected at least 1 bean which qualifies as autowire candidate.
Dependency annotations: {}
의미 :: 이 에러 메시지는 Spring이 'list'라는 메서드의 첫 번째 파라미터로 주입하려는 org.springframework.ui.Model 타입의 빈(bean)을 찾지 못했다는 의미
원인 ::
1) 본인은 AService 타입의 Aservice에 @Autowired를 통해서 의존성을 주입하려고 했으나 그걸 하지 못하였고 그로인해서 코드에서는 jsp 화면으로 보내주는 Model 타입의 model에 대한 빈을 컨테이너에서 찾으려고 해서 발생하게 되었음
그러나 Model은 스프링 MVC에서 요청이 들어올 때 자동으로 전달되는 인스턴스이지, 별도의 빈으로 등록되어 있지 않으므로 의존성 주입 대상이 아님.
그래서 @Autowired를 붙이면 아래와 같이 빈을 찾을 수 없다는 의미인 NoSuchBeanDefinitionException 에러가 발생하게 됩니다.
해결 방법
1) Service와 연결하는 방법
애초에 목적이 Service와 연결하는 것이 목적이였다면 , @Autowired 어노테이션을 선언하고 Service를 연결하여 의존성을 주입하면 해결된다.
@Controller
public class SampleController {
@Autowired
private AService aService;
@GetMapping("/example")
public String example(Model model) {
// aService를 활용한 로직
return "exampleView";
}
}
위의 코드는 service 를 통해 비즈니스 로직을 거친 후 모든 과정을 끝낸 후 exampleView.jsp로 보낸다.
2. @Autowired 삭제하는 방법
@Controller
public class SampleController {
@GetMapping("/example")
public String example(Model model) {
return "exampleView";
}
}
위의 코드는 비즈니스 로직이 아닌 GetMapping을 통해서 exampleView.jsp의 화면을 보여준다 .
쉽게 예시를 들면 MVC 프로젝트의 HomeController를 생각하면 된다.
'스프링' 카테고리의 다른 글
| [Spring] tomcat 연결 후 브라우저 설정 (0) | 2025.01.20 |
|---|---|
| sts와 이클립스 설치 관련, STS3 Legacy Project (0) | 2025.01.20 |
| [스프링 ]security (0) | 2024.11.29 |
| 절대 경로와 상대 경로의 차이 (0) | 2024.11.27 |
| [Spring] MVC(VO객체 통해서 데이터의 흐름 알아보기 ) (0) | 2024.11.20 |