Spring/웹 개발 101
2.2.5 서비스 레이어 : 비즈니스 로직
cosmohoo
2022. 4. 10. 00:20
반응형
서비스 레이어 : 컨트롤러와 퍼시스턴스 사이에서 비즈니스 로직을 수행하는 역할
@service 어노테이션 : 스프링 컴포넌트이며 기능적으로 비즈니스 로직을 수행하는 서비스 레이어임을 알려주는 어노테이션
* @Component와 기능적으로는 크게 차이가 없다.
package com.example.demo.service;
import org.springframework.stereotype.Service;
@Service
public class TodoService {
public String testService() {
return "Test Service";
}
}
package com.example.demo.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.http.ResponseEntity;
import com.example.demo.dto.ResponseDTO;
import com.example.demo.service.TodoService;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
@RestController
@RequestMapping("todo")
public class TodoController {
//testTodo메서드 작성하기
@Autowired
private TodoService service;
@GetMapping("/test")
public ResponseEntity<?> testTodo(){
String str = service.testService();//테스트 서비스 사용
List<String> list = new ArrayList<>();
list.add(str);
ResponseDTO<String> response = ResponseDTO.<String>builder().data(list).build();
return ResponseEntity.ok().body(response);
}
}

=>@RestController내부도 @Component 어노테이션을 갖고 있습니다.
=> @Service, @RestController 모두 자바 빈이고 스프링이 관리합니다.
=> 스프링을 TodoController 오브젝트를 생성할 때 TodoController내부에 선언된 TodoService에 @Autowired 어노테이션이 붙어 있다는 것을 확인합니다.
=> @Autowired가 알아서 빈을 찾은 다음그 빈을 이 인스턴스 멤버 변수에 연결하나는 뜻입니다.
반응형