문제상황:
Spring Boot를 사용하여 개발을 진행하던 중, 서비스 레이어에서 의존성 주입을 위해 @Autowired 어노테이션을 사용했습니다. 하지만 ProductService 클래스에 @Service 어노테이션이 누락되어 있어서 아래와 같은 에러 로그가 발생했습니다.
에러가 발생한 코드:
// ProductService.java
package com.example.demo.service;
import com.example.demo.domain.Product;
import com.example.demo.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
public class ProductService {
@Autowired
private ProductRepository productRepository;
public List<Product> findAll() {
return productRepository.findAll();
}
}
// ProductController.java
package com.example.demo.controller;
import com.example.demo.domain.Product;
import com.example.demo.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class ProductController {
@Autowired
private ProductService productService;
@GetMapping("/products")
public List<Product> getAllProducts() {
return productService.findAll();
}
}
에러로그 내용:
***************************
APPLICATION FAILED TO START
***************************
Description:
Field productService in com.example.demo.controller.ProductController required a bean of type 'com.example.demo.service.ProductService' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.example.demo.service.ProductService' in your configuration.
해결방법:
에러가 수정된 코드+ 수정된 부분에 대한 주석:
// ProductService.java
package com.example.demo.service;
import com.example.demo.domain.Product;
import com.example.demo.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service // 누락된 @Service 어노테이션 추가
public class ProductService {
@Autowired
private ProductRepository productRepository;
public List<Product> findAll() {
return productRepository.findAll();
}
}
원인분석:
에러 발생 원인은 ProductService 클래스에 @Service 어노테이션이 누락되어, 스프링이 해당 클래스를 빈으로 등록하지 않았기 때문입니다. 이로 인해, ProductController에서 ProductService를 주입받지 못해 위와 같은 에러가 발생했습니다.
@Service 어노테이션은 스프링이 해당 클래스를 서비스 레이어의 컴포넌트로 인식하고 빈으로 등록하게 해주는 어노테이션입니다. 이를 추가함으로써 에러를 해결할 수 있습니다.
참고링크:
728x90