👉 객체나 메소드의 생성주기(프로그램의 흐름)를 컨테이너가 관리 → 제어의 역전
@Component
는 다른 스테레오 타입 어노테이션들의 상위 개념으로 사용됨@Service
, @Repository
, @Controller
등의 어노테이션들은 @Component
를 기반으로 함import org.springframework.stereotype.Component;
@Component // 평범한 bean 객체 (스프링한테 bean 객체라고 알려줌) IOC 등록하고 싶은 객체
public class AppComponent {}
@Repository
public class AppRepository {
//데이터베이스와 소통을 담당
public List<Object> selectStudentAll(){
return new ArrayList<>();
}
}
@Service
public class AppService {
// 주된 비즈니스 로직이 구현되는 공간
// Controller -> Service
// 1. 데이터베이스 조회
// 2. Component 사용
// 3. 모은 데이터를 가지고 응답 (의사결정)
private final AppRepository repository; //Service는 보통 repository와 소통
public AppService(AppRepository repository) {
this.repository = repository;
}
public List<Object> readStudentAll(){
List<Object> queryResult = repository.selectStudentAll();
return queryResult;
}
}
@Controller
@RestController
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
// 모든 메소드에 @ResponseBody를 붙이는 용도
public class AppController {
// 사용자의 입력을 받는 요소
private final AppService service;
public AppController(AppService service) {
this.service = service;
}
@GetMapping("create")
public @ResponseBody String create() {
this.service.createStudent(
"sanghun",
33,
"010-1234-5678",
"bdns@gmail.com"
);
return "done";
};
@GetMapping("read-all")
public @ResponseBody String readAll() {
this.service.readStudentAll();
return "done-read-all";
}
@GetMapping("read")
public @ResponseBody String readOne() {
this.service.readStudent(1L);
return "done-read-one";
}
@GetMapping("update")
public @ResponseBody String update(){
this.service.updateStudent(1L,"panghun");
return "done-update";
}
@GetMapping("find")
public @ResponseBody String find(){
this.service.findAllByTest();
return "done-find";
}
}
import org.springframework.context.annotation.Configuration;
@Configuration //Spring을 활용하는데 필요한 다양한 설정을 담고있음
public class AppConfiguration {
}
Configuration
내부에서 정의한 메소드의 결과만 따로 Bean 객체로서 관리@Configuration
public class AppConfig {
@Bean
public AppConfigData connectionUrl(){
if (/* 통신이 정상적으로 이뤄지는지 확인 */)
return new AppConfigData("main-url");
else return new AppConfigData("backup-url");
}
}
@Bean | @Component |
---|---|
메소드에 사용 | 클래스에 사용 |
개발자가 컨트롤이 불가능한 외부 라이브러리 사용 시 사용 | 개발자가 직접 컨트롤이 가능한 내부 클래스에 사용 |
두번째 @Service가 @Controler 아닌가요?