예를 들어 Repository에서 id, pw를 파라미터로 받아야 하는 조건이 생기는 경우 service, controller 에서도 id, pw가 필요해진다.
스프링 프레임워크는 DI 방식을 사용할 수 있도록 객체를 생성하는 기능을 제공한다.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class BeanConfiguration {
@Bean
public ProductRepository productRepository() {
String dbId = "sa";
String dbPassword = "";
String dbUrl = "jdbc:h2:mem:springcoredb";
return new ProductRepository(dbId, dbPassword, dbUrl);
}
@Bean
@Autowired
public ProductService productService(ProductRepository productRepository) {
return new ProductService(productRepository);
}
}
public class ProductRepository {
private String dbId;
private String dbPassword;
private String dbUrl;
// 생성자
public ProductRepository(String dbId, String dbPassword, String dbUrl) {
this.dbId = dbId;
this.dbPassword = dbPassword;
this.dbUrl = dbUrl;
}
...
}
public class ProductService {
// 멤버 변수 선언
private final ProductRepository productRepository;
// 생성자: ProductService() 가 생성될 때 호출됨
@Autowired
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 {
Product product = productRepository.getProduct(id);
if (product == null) {
throw new NullPointerException("해당 아이디가 존재하지 않습니다.");
}
int myPrice = requestDto.getMyprice();
productRepository.updateProductMyPrice(id, myPrice);
return product;
}
}
@RestController // JSON으로 응답함을 선언합니다.
public class SearchRequestController {
private final NaverShopSearch naverShopSearch;
@Autowired
public SearchRequestController(NaverShopSearch naverShopSearch) {
this.naverShopSearch = naverShopSearch;
}
@GetMapping("/api/search")
public List<ItemDto> getItems(@RequestParam String query) {
String resultString = naverShopSearch.search(query);
return naverShopSearch.fromJSONtoItems(resultString);
}
}