상세 컨텐츠

본문 제목

User Service API 추가-User Domain 생성 및 GET API편

Spring/도원리 스프링

by 빙하둘리 2023. 1. 15. 18:57

본문

728x90

User Service API 추가

-User Domain 생성

-GET

-POST

-Exception Handling

-DELETE

 

폴더 구조

User code

package com.example.restfulwebservice.user;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.Date;

@Data
@AllArgsConstructor
public class User {
    private Integer id;
    private String name;
    private Date joinDate;
}

 

UserDaoService

package com.example.restfulwebservice.user;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class UserDaoService {
    private static List<User> users = new ArrayList<>();

    private static int usersCount=3;

    static {
        users.add(new User(1,"Kenneth",new Date()));
        users.add(new User(2,"Alice",new Date()));
        users.add(new User(3,"Elena",new Date()));
    } // db에 3명 들어가 있다고

    // 사용자 전체 목록 전달
    public List<User> findAll() {
        return users;
    }

    public User save(User user) {
        if(user.getId()==null){ // 기본키에 해당하는 id 미존재시
            user.setId(++usersCount);
        }
        users.add(user);
        return user;
    }
    // 개별 사용자 조회
    public User findOne(int id) {
        for(User user: users){
            if(user.getId()==id){
                return user;
            }
        }
        return null;
    }
}

 

그리고 UserDaoService를 Service로 쓸 수 있게 @Service를 추가하자

@Service
public class UserDaoService {

빈의 용도를 정확히 알 수 있게 함

 

그 다음으로는 사용자 요청을 처리할 수 있는 Controller 클래스를 추가해보자

폴더 구조는 다음과 같다

 

UserController 클래스

package com.example.restfulwebservice.user;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class UserController {
    // 비즈니스 메서드 호출하려고 함
    private UserDaoService service;

    // 의존성 주입으로 빈 만들어
    public UserController(UserDaoService service){
        this.service=service;
    }

    @GetMapping("/users")
    public List<User> retrieveAllUsers() {
        return service.findAll(); // 전체 사용자 목록 반환
    }


    // 사용자 한명 반환
    // GET / users/1 or /users/10 -> String
    @GetMapping("/users/{id}")
    public User retrieveUser(@PathVariable int id) // 문자형이 int형으로 자동으로 매핑 된다.
    {
        return service.findOne(id);
    }

}

의존성 주입이 잘 되었다.

 

localhost:8080/users로 조회하면

전체 사용자 목록을 조회하는 retrieveAllUsers라는 함수가 작동된다.

그 다음에 개별 사용자 목록을 확인할 수 있게끔 해보자.

조회가 잘 됨을 알 수 있다.

코드 분석해보자!

 

728x90

'Spring > 도원리 스프링' 카테고리의 다른 글

POST 사용자 등록하기 편  (0) 2023.01.16
path variable 사용  (0) 2023.01.15
DispatcherServlet  (0) 2023.01.15

관련글 더보기

댓글 영역