💻 Programming/Spring

[Spring] Service와 Repository 구현하기 & 3계층 연결

soozkim 2023. 11. 5. 12:33
10번째 과제

1. 스프링 빈(Spring Bean) 등록 방법

스프링 IoC 컨테이너는 클래스에서 어노테이션을 보고 클래스의 인스턴스를 만든다. 이러한 인스턴스를 빈(Bean)이라고 한다.

스프링 빈을 등록하는 방법에는 2가지가 있다.

 

첫 번째, @Configuration + @Bean 조합

두 번째, @Component 스캔

 

두 번째 방법인 컴포넌트 스캔은 Service와 Repository 에 어노테이션으로 스프링 빈을 등록해주고 Autowired를 설정해주면, 자동으로 의존 관계를 주입해주는 방식이다.

 

스프링 빈으로 등록되면 DI를 요청할 수 있고, DI를 요청하는 방법은 필드 위에 @Autowired를 적어주면 된다.

@Controller
class Controller{
    @Autowired
    Service service;
}

 

 

2. Service, Repository 구현하고 DI를 활용하여 3계층 흐름 만들기

이 글에서는 스프링 빈 등록 방법 중 두 번째 방법을 사용하여 Service와 Repository를 구현하였다. 

이제 3계층 흐름을 만드는 과정을 살펴볼 것이다. 화면에서 이 전 게시글과 같이 TEST라는글자를 출력하려고 한다.

 

1) Service와 Repository 파일을 생성하기

Service와 Repository 패키지를 각각 생성해주고 그 안에 파일을 생성한다.

 

2) Controller -> Service -> Repository -> Service -> Controller 흐름 만들기

 

Service와 Repository 파일을 생성했으면 @Service와 @Repository 어노테이션을 통해 스프링 빈을 등록해준다.

@Service
public class TestService {
}
@Repository
public class TestRepository {
}

 

Repository

TestRepository에 화면에 출력할 TEST 문자열을 반환해주는 find() 메서드를 정의해준다.

package com.example.demo.repository;

import org.springframework.stereotype.Repository;

@Repository
public class TestRepository {

    public String find() {
        return "TEST";
    }
}

 

 

*** @Repository 어노테이션 코드에서도 @Component를 확인할 수 있다. 따라서 @Repository를 작성해주면 자동으로 컴포넌트 스캔을 해주어 DI를 해줄 수 있게 된다.

@Repository 어노테이션

Service

TestService 파일에 Repository로 연결해주기 위해 TestRepository를 선언해주고 @Autowired로 DI를 요청해준다. 그리고 서비스의 find() 메서드를 TestRepository의 find 메서드로 리턴해주도록 정의한다.

package com.example.demo.service;

import com.example.demo.repository.TestRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class TestService {
    @Autowired
    TestRepository testRepository;

    public String find() {
        return testRepository.find();
    }
}

 

*** @Service 어노테이션 코드에서도 @Component를 확인할 수 있다. 따라서 @Service를 작성해주면 자동으로 컴포넌트 스캔을 해주어 DI를 해줄 수 있게 된다.

@Service 어노테이션

Controller

마지막으로 Controller에 Service 필드에 @Autowired를 적어주어 DI 요청을 한다. 컨트롤러의 test메서드에서 testService.find()를 리턴해주어 Service로 연결해준다. /test 주소가 매핑되면 TestService 파일의 find() 메서드를 찾도록 연결될 것이 예상된다.

package com.example.demo.controller;

import com.example.demo.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

//@Controller
@RestController
public class TestController {

    @Autowired
    TestService testService;

    @GetMapping("/test")
    public String test(){
        return testService.find();
    }
}

 

@RestController에는 @Controller와 @ResponseBody 어노테이션이 결합되어 있다.

@RestController 어노테이션

 

그리고 @Controller에는 @Component 어노테이션이 적혀있는 것을 확인할 수 있다.

@Controller 어노테이션

 

이렇게 3계층을 연결한 방법으로 실행하면 성공적으로 TEST가 출력된 화면을 확인할 수 있다.

 

728x90