Spring Tools for Eclipse 기준 설명

1. https://spring.io/tools 접속하여 STS(for Eclipse) 설치 후 실행
2. 상단 Quick Access에 Git Repositories 검색 후 클릭
3. Git Repositories 탭으로 가서 Clone a Git repository
4. gitlab 사이트 Import 하려는 프로젝트로 들어가서 Clone -> Clone with HTTPS 부분 복사
5. STS로 돌아가서 URL 부분에 붙여넣기 하면 세부 항목까지 자동 입력(Port는 빈칸)
6. master 브랜치 체크 후 Next & Finish
7. Git Repositories 탭의 프로젝트 우클릭 후 Import Projects
8. Package Explorer에 받아진 프로젝트 확인
9. Window > Preferences > Server > Runtime Environments > 우측 Add > Tomcat 버전 선택 > Browse...
   클릭 후 다운로드한 Tomcat 폴더 선택 > Finish > Apply and Close

   (Tomcat 다운로드 https://tomcat.apache.org)
10. 상단 Quick Access에 Servers 검색 후 클릭
11. Servers 탭에서 우클릭 > New > Server > Tomcat 버전 선택 > Available 부분에 있는 항목 선택 후 Add > Finish
12. Project는 우클릭 후 Maven > Update Project...와 최상단 탭 Project > Clean...

13. x 표시가 사라지지 않는다면 설치되지 않은 플러그인이 있는지 확인

     - Lombok을 사용하는 경우 -

     Eclipse의 경우 Maven / Gradle에 Lombok Dependency가 추가되어 있어도 Lombok을 따로 설치해 줘야 한다.

     https://projectlombok.org/download 접속하여 다운로드한다.

     다운로드한 lombok.jar 파일을 STS 실행파일이 있는 위치로 옮긴다.

     명령 프롬프트(CMD)를 관리자 권한으로 실행시킨 후 lombok.jar 파일이 위치한 폴더로 이동한다.

      lombok.jar 파일이 C:\STS\contents\stsRELEASE  폴더 안에 있다면

      cd C:\STS\contents\stsRELEASE 명령어로 이동 후 java -jar lombok.jar

      Lombok을 설치할 IDE를 체크한 후 Install / Update 버튼을 클릭, 설치가 끝났다면 실행 중인 STS를 재실행

      STS 실행파일 위치에 실행파일명.ini 파일 열어보면 -javaagent: 부분에 lombok.jar 경로가 추가된 것 확인

14. 13번에서 추가로 설치한 플러그인이 있다면 12번으로 간다.
15. Servers 탭의 Tomcat 더블클릭 후 Overview 탭 Ports의 HTTP 부분 옆 Port Number 변경

     & Modules 탭의 Path를 / 로 변경
16. Servers 탭의 Tomcat 우클릭 > Clean...

17. Start the server 후 브라우저 실행하여 localhost:8080 입력 (Port Number가 8080일 경우)

Spring Security의 Bcrypt 암호화를 사용해 만든 비밀번호를 유저 테이블에 저장할 때
입력한 비밀번호에 랜덤한 salt 값이 더해져 암호화되는 것을 알 수 있다.

(같은 비밀번호로 변경해도 저정되는 값이 다르기 때문)
그렇다면 입력한 비밀번호 외에 암호화에 사용된 salt 값이 어떤 값인지, 그 값은 어디에 저장되는지 알아야 한다.
하지만 Bcrypt 암호화의 salt 값따로 저장되는 게 아닌 해시값에 이어붙여 함께 저장되기 때문에 따로 salt 값 저장이

필요하지 않다.


$2a$10$Yz4die0hPMjS3.6njaxmmOyrwArwsC9NEs5kwOI0Gh04uLjHaON2e
위와 같은 형태로 해시값을 생성하는데 이는 '$'로 구분되는 3가지의 필드라고 보면 된다.

'2a'는 사용된 bcrypt알고리즘의 버전을 의미하며
'10'은 cost factor이다. cost factor가 10이라는 의미는 key derivation 함수가 2^10번 반복 실행된다는 의미로 이 값이 커질 수록 해시값을 구하는 속도가 느려진다.
'Yz4die0hPMjS3.6njaxmmOyrwArwsC9NEs5kwOI0Gh04uLjHaON2e'가 바로 salt 값과 암호화된 비밀번호 값이다.

'Framework > Spring Security' 카테고리의 다른 글

[Framework] Spring Security 세션값 변경  (0) 2023.07.19
AppLoginUser pmUser = null;

if(pmList.isEmpty() == false) {
	PmVO pmVo = pmList.get(0);
    
	List<GrantedAuthority> authList = new ArrayList<>();
    
    	if(pmVo != null) {
        
            List<SecurityRole> roles = new ArrayList<SecurityRole>(); 
            
            roles.add(SecurityRole.USER); // 기본권한
            
            if(pmVo.isLoginAble()) {
            	roles.add(SecurityRole.PM); // PM권한
            }
            
            List<String> adminEmails = new ArrayList<String>();
            adminEmails.add("champcom90@gmail.com");
            
            if(adminEmails.contains(pmVo.getId())) {
            	roles.add(SecurityRole.ADMIN); // 관리자권한
            }
            
            // 권한 ENUM을 시큐리티 ROLE로 변환
            for(SecurityRole r : roles) {
            	authList.add(new SimpleGrantedAuthority(r.getValue())); 
            }
    	}
        
        pmUser = AppLoginUser.ofPm(pmVo, authList);
        
        springUserSupportService.bindProjectScope(pmUser);
        
        pmUser.setLoginIp(UtilRequest.getClientIp()); // 로그인한 IP설정
        
        Authentication authentication = new UsernamePasswordAuthenticationToken(pmUser, null, pmUser.getAuthorities());
        
        SecurityContext securityContext = SecurityContextHolder.getContext();
        
        securityContext.setAuthentication(authentication);
        
        session.invalidate(); // 세션 초기화(로그인 후 세션값 변경되어야 하며 로그인 상태에서의 세션값은 고정이어야 한다.)
        
        session = request.getSession(); // 세션 재발급(로그인 후 세션값 변경되어야 하며 로그인 상태에서의 세션값은 고정이어야 한다.)
        
        // session.setAttribute("SPRING_SECURITY_CONTEXT", securityContext); // 이전에는 SPRING_SECURITY_CONTEXT 속성에 바로 접근해서 세션값 변경하는 게 가능했지만 지금은 불가능

session.invalidate(); // 세션 초기화


session = request.getSession(); // 세션 재발급

Spring은 Spring Triangle이라고 부르는 핵심 3대 요소를 제공한다.

 

 

핵심 3대 요소에 대해 알아보기 전에 POJO란 무엇인지 먼저 알아보자

 

POJO(Plain Old Java Object 오래된 방식의 간단한 자바 오브젝트) : 특정 기술에 종속되지 않는 순수한 자바 객체를

의미한다. 예를 들어, 특정 기술을 사용하기 위해 특정 프레임워크를 의존하게 되면 그것은 POJO라고 할 수 없다.

특정 기술에 종속되어 있기 때문이다.

 

POJO의 예

public class UserDTO {
	
	private String userName;
	private String userId;
	private String userPassword;
	
	public String getUserName() {
		return userName;
	}
	
	public void setUserName(String userName) {
		this.userName = userName;
	}
	
	public String getUserId() {
		return userId;
	}
	
	public void setUserId(String userId) {
		this.userId = userId;
	}
	
	public String getUserPassword() {
		return userPassword;
	}
	
	public void setUserPassword(String userPassword) {
		this.userPassword = userPassword;
	}
}

위 객체는 기본적인 자바 기능인 getter, setter 기능만 가지고 있다.

특정 기술에 종속되어 있지 않은 순수 자바 객체이기 때문에 위 객체는 POJO라고 할 수 있다.

 

POJO가 아닌 예

public class Sample extends WindowAdapter {

	@Override
	public void windowClosing(WindowEvent e) {
		System.exit(0);
	}
}

Window의 기능을 사용하기 위해 WindowAdapter 클래스를 상속받았기 때문에 POJO라고 할 수 없다.

이렇게 되면 다른 솔루션을 사용하고자 할 때 많은 양의 코드를 리팩토링해야 하는 문제가 있다.

 

이처럼 특정 기술과 환경에 종속되어 의존하게 되면, 코드 가독성 뿐만 아니라 유지보수, 확장성에도 어려움이 생긴다.

이러한 객체지향의 장점을 잃어버린 자바를 되살리기 위해 POJO라는 개념이 등장한 것이다.

 

진정한 POJO란 객체지향적인 원리에 충실하면서, 환경과 기술에 종속되지 않고 필요에 따라 재활용될 수 있는 방식으로

설계된 오브젝트이다. - 토비의 스프링 -

 

POJO는
A. 미리 지정된 클래스를 extends 하면 안 된다.
B. 미리 정의된 인터페이스를 implements 하면 안 된다.
C. 미리 정의된 Annotation을 포함하면 안 된다.

 

POJO의 장점
특정 규약에 종속되지 않아 객체지향 설계를 할 수 있다.
특정 환경에 종속되지 않아 테스트하기 좋다.
특정 규약에 종속되지 않아 낮은 레벨 코드와 비즈니스 코드가 분리되어 깔끔한 코드 작성이 가능하다.

 

애플리케이션을 구성하는 객체(Bean)가 생성되고 동작하는 틀을 제공해 줄 뿐만 아니라,

애플리케이션 코드를 어떻게 작성해야 하는지에 대한 기준도 제공한다.

이를 일반적으로 프로그래밍 모델이라고 부르는데, Spring에는 크게 3가지 핵심 프로그래밍 모델을 지원한다.

 

1. AOP(Aspect Oriented Programming 관점 지향 프로그래밍) : 여러 객체에 공통으로 적용할 수 있는 기능을

구분함으로써 재사용을 높여주는 프로그래밍 기법이다. AOP는 핵심 기능과 공통 기능의 구현을 분리함으로써

핵심 기능을 구현한 코드의 수정 없이 공통 기능을 적용할 수 있게 만들어준다.

 

 

2. PSA(Portable Service Abstraction 서비스 추상화) : 환경의 변화와 관계없이 일관된 방식의 기술로의 접근 환경을

제공하는 추상화 구조를 말한다. 이는 POJO 원칙을 철저히 따른 Spring의 기능으로 Spring에서 동작할 수 있는

Library들은 POJO 원칙을 지키도록 PSA 형태의 추상화가 되어있음을 의미한다.
잘 만든 인터페이스 하나가 열 클래스 부럽지 않다. PSA를 '잘 만든 인터페이스'라고도 한다.
PSA가 적용된 코드는 나의 코드가 바뀌지 않고, 다른 기술로 간편하게 바꿀 수 있도록 확장성이 좋고
기술에 특화되어 있지 않는 코드를 의미한다.
Spring은 Spring Web MVC, Spring Transaction, Spring Cache 등 다양한 PSA를 제공한다.

 

Spring Web MVC

             @Component

                     @Controller

                     @Repository

                     @Service

            ● @RequestMapping

            ● ...

● Spring Transaction

            ● JDBC

            ● JPA

● Spring Cache

            ● Cacheable

            ● CacheEvict

...

 

3. IoC / DI

IoC(Inversion of Control 제어의 역전) : 이는 Spring뿐만 아니라 모든 프로그래밍에서 사용될 수 있는 범용적인 개념이다.

쉽게 말해 객체의 제어권이 개발자 본인이 아닌 Spring 컨테이너에게 넘어가는 것이다.

 

다음은 일반적으로 자바에서 객체를 생성하여 객체를 제어하는 코드이다.

class ClassA {
		
}

class ClassB{
	
    private ClassA a;
    
    ClassB() {
    	this.a = new ClassA();
    }
}

보다시피 개발자 본인이 new 연산자를 통해 직접 객체를 생성하고 변수에 할당해 줘야 하는 방식이다.

 

Spring의 경우는 어떨까?

 

다음은 Spring에서의 객체 할당 방식이다.

@Component
class ClassA {
		
}

class ClassB{
	
    @Autowired
    private ClassA a;
 
}

Spring의 경우 Bean(Spring에 의해 관리되는 객체)이라면 @Autowired 어노테이션을 통해 손쉽게 객체를 할당할 수 있다.

이는 개발자 본인이 객체를 관리하는 것이 아닌 Spring 컨테이너에서 객체를 생성하고 해당 객체를 할당 시켜준 것이다.

이처럼 객체의 흐름, 생명주기 관리 등을 외부(제3자)에서 처리하는 방식의 모델을 제어의 역전(IoC)라고 한다.

 

제어의 역전 개념을 이용하면 프레임워크와 라이브러리의 구분 또한 가능하다.

프레임워크가 내가 작성한 코드를 제어하고, 대신 실행하면 그것은 프레임워크가 맞다.(JUnit)

반면에, 내가 작성한 코드가 직접 제어의 흐름을 담당한다면 그것은 프레임워크가 아니라 라이브러리이다.

 

DI(Dependency Injection 의존성 주입) : 객체를 외부로부터 할당받고 이를 통해 객체를 동적으로 할당하는 방식이다.

사용할 객체들을 컨테이너에 등록한 후 애플리케이션 코드에서 해당 객체를 setter 함수의 매개변수로 받아와서

실행 시 동적으로 의존관계를 설정해 준다.

 

의존성 주입 방식에는 3가지가 있다.

A. 생성자를 이용한 의존성 주입

B. setter 메소드를 이용한 의존성 주입

C. 초기화 인터페이스를 이용한 의존성 주입

 

Spring에서는 두 번째 방식인 setter 메소드를 이용한 의존성 주입을 지지한다.

외부에서 제공받은 객체를 저장해뒀다가 내부의 메소드에서 사용하도록 하는 DI 방식에서 활용하기 좋기 때문이다.

 

이 IoC와 DI 덕분에 캡슐화를 통한 높은 응집도와, 객체 간의 낮은 결합도를 이루고 유연한 코드를 작성할 수 있도록

해주며, 개발자들이 개발에 더욱 집중할 수 있도록 해준다.

의존성 주입 방식

 

1. @Autowired (필드 주입 : Field Injection)

참고 : 필드를 final로 선언 불가

@Service
public class ArticleService {

  @Autowired
  private ArticleRepository articleRepository;
}

 

2. private final (생성자 주입 : Constructor Injection)

@Service
public class ArticleService {

  private final ArticleRepository articleRepository;

  public ArticleService(ArticleRepository articleRepository) {
    this.articleRepository = articleRepository;
  }
}

 

private final 방식이 더 좋은 이유

1. 순환 참조를 방지할 수 있다. (순환 참조 발생 시, Application이 구동되지 않는다.)

2. 테스트에 용이하다.

3. final 선언이 가능해 불변성이 보장된다.

4. 코드의 품질을 높일 수 있다.

5. 오류를 방지할 수 있다.

Spring Boot에서 JWT를 활용한 인증 구현

세션 VS 토큰

 

[세션]

1. 클라이언트가 로그인 요청을 하고, 로그인 정보가 일치하면 서버는 세션을 생성/유지 (클라이언트마다 하나씩)

(세션에는 사용자 ID, 로그인 시간, IP 등을 저장)

2. 서버는 로그인 응답 (세션을 찾을 수 있는 세션 ID를 클라이언트에 전달 (보통 쿠키로 전달))

(세션은 서버에 저장되는 값, 쿠키는 클라이언트에 저장되는 값)

3. 클라이언트가 세션 ID와 함께 서비스 요청을 하면 서버는 세션 ID로 세션을 찾아 인증된 유저임을 확인

4. 서버는 서비스 응답

서버가 세션을 들고있다.

 

서버가 1대라면 세션을 사용해도 괜찮지만, 서버는 여러 대가 존재할 것이다. (모두 세션을 가져야 함 & 동기화)

세션 클러스터링 등 작업이 복잡하며 DB에도 부담을 줄 수 있다.

 

[토큰]

1. 클라이언트가 로그인 요청을 하면 서버는 토큰을 생성 (클라이언트마다 하나씩)

2. 서버는 토큰과 함께 로그인 응답

3. 클라이언트가 토큰과 함께 서비스 요청을 하면 서버는 토큰으로 인증된 유저임을 확인

4. 서버는 토큰과 함께 서비스 응답

클라이언트와 서버가 토큰을 주고 받는다.

 

build.gradle의 dependencies에 아래의 코드 추가

implementation 'javax.xml.bind:jaxb-api:'
implementation 'io.jsonwebtoken:jjwt-api:0.11.5'
runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.11.5'
runtimeOnly 'io.jsonwebtoken:jjwt-jackson:0.11.5'

SecurityController

package com.example.firstproject.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.LinkedHashMap;
import java.util.Map;

@RestController
@RequestMapping("/security")
public class SecurityController {

    @Autowired
    private SecurityService securityService;

    @GetMapping("/create/token")
    public Map<String, Object> createToken(@RequestParam(value = "subject") String subject) { // 일반적으로 subject를 ID 값으로, PW를 key 값으로 같이 보내는 POST 방식이 맞지만 여기서는 확인을 위해 GET 방식으로 한다.
        String token = securityService.createToken(subject, (2 * 1000 * 60)); // 2분
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("result", token);
        return map;
    }

    @GetMapping("/get/subject")
    public Map<String, Object> getSubject(@RequestParam(value = "token") String token) {
        String subject = securityService.getSubject(token);
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("result", subject);
        return map;
    }
}

SecurityService

package com.example.firstproject.security;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Service;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;

@Service
public class SecurityService {
    private static final String SECRET_KEY = "qweqiwehqhruhqwiejqiwejqiwheuqfjnqweojqwiejqwuequwe";

    // 로그인 서비스 보낼 때 같이
    public String createToken(String subject, long expTime) {

        if (expTime <= 0) {
            throw new RuntimeException("만료 시간은 0보다 커야합니다.");
        }

        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

        byte[] secretKeyBytes = DatatypeConverter.parseBase64Binary(SECRET_KEY);

        Key signingKey = new SecretKeySpec(secretKeyBytes, signatureAlgorithm.getJcaName());

        return Jwts.builder()
                   .setSubject(subject)
                   .signWith(signingKey, signatureAlgorithm)
                   .setExpiration(new Date(System.currentTimeMillis() + expTime))
                   .compact();
    }

    // 실제로 사용할 때는 안에 있는 로직을 이용해 boolean 타입을 리턴하는 토큰 검증 메소드를 만들고 토큰 검증 로직에서 이 메소드를 호출해서 사용
    public String getSubject(String token) {
        Claims claims = Jwts.parserBuilder()
                            .setSigningKey(DatatypeConverter.parseBase64Binary(SECRET_KEY))
                            .build()
                            .parseClaimsJws(token)
                            .getBody();

        return claims.getSubject();
    }
}

POSTMAN 테스트

1. /create/token

 

2. /get/subject

 

3. /get/subject 토큰 유지 시간으로 설정한 2분이 지나면

TDD(Test Driven Development)란?

테스트 코드를 만들고, 이를 통과하는 최소한의 코드로 시작하여

점진적으로 개선, 확장해가는 개발 방식을 말한다.

 

Article 서비스를 검증하는 테스트 코드를 작성해보자

 

Article 서비스에서 테스트를 원하는 메소드명 우클릭 Generate > Test를 클릭하고

열린 창 하단에 테스트를 할 메소드명을 체크 후 OK를 클릭한다.

 

ArticleServiceTest라는 클래스 파일이 만들어지고

이 파일의 경로는 src > test > java > com.example.firstproject > service가 된다.

 

H2 DB를 사용하고 있었기 때문에 data.sql을 참고해 테스트 코드를 작성한다.

 

예상 시나리오 작성 -> 실제 결과와 비교하여 검증

 

<data.sql>

INSERT INTO ARTICLE(ID, TITLE, CONTENT) VALUES (2, 'AAAA', '1111');
INSERT INTO ARTICLE(ID, TITLE, CONTENT) VALUES (3, 'BBBB', '2222');
INSERT INTO ARTICLE(ID, TITLE, CONTENT) VALUES (4, 'CCCC', '3333');

<ArticleServiceTest>

package com.example.firstproject.service;

import com.example.firstproject.dto.ArticleDto;
import com.example.firstproject.entity.Article;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;

@SpringBootTest // 해당 클래스는 스프링부트와 연동되어 테스팅된다.
class ArticleServiceTest {

    @Autowired ArticleService articleService;

    @Test
    void readAll() {
        // 예상
        Article a = new Article(2L, "AAAA", "1111");
        Article b = new Article(3L, "BBBB", "2222");
        Article c = new Article(4L, "CCCC", "3333");
        List<Article> expectedList = new ArrayList<Article>(Arrays.asList(a, b, c));

        // 실제
        List<Article> articleList = articleService.readAll();

        // 비교
        assertEquals(expectedList.toString(), articleList.toString());
    }

    @Test
    void read_success() { // read 메소드 성공 테스트
        // 예상
        Long id = 2L;
        Article expected = new Article(id, "AAAA", "1111");

        // 실제
        Article article = articleService.read(id);

        // 비교
        assertEquals(expected.toString(), article.toString());
    }

    @Test
    void read_fail() { // read 메소드 실패 테스트 // 존재하지 않는 id를 입력한 경우
        // 예상
        Long id = -1L;
        Article expected = null;

        // 실제
        Article article = articleService.read(id); // return articleRepository.findById(id).orElse(null); 이렇게 작성되어 있으므로 null 값을 갖는 expected로 비교

        // 비교
        assertEquals(expected, article); // null은 toString 메소드를 호출할 수 없음
    }

    @Test
    @Transactional // 조회가 아닌 생성, 변경, 삭제의 경우 Transaction으로 묶어서 Rollback할 수 있게 처리해줘야 한다.
    void create_success() { // create 메소드 성공 테스트 // title과 content만 있는 dto 입력
        // 예상
        String title = "DDDD";
        String content = "4444";
        ArticleDto dto = new ArticleDto(null, title, content);
        Article expected = new Article(1L, title, content);

        // 실제
        Article article = articleService.create(dto);

        // 비교
        assertEquals(expected.toString(), article.toString());
    }

    @Test
    @Transactional // 조회가 아닌 생성, 변경, 삭제의 경우 Transaction으로 묶어서 Rollback할 수 있게 처리해줘야 한다.
    void create_fail() { // create 메소드 실패 테스트 // id가 포함된 dto 입력
        // 예상
        String title = "DDDD";
        String content = "4444";
        ArticleDto dto = new ArticleDto(2L, title, content);
        Article expected = null;

        // 실제
        Article article = articleService.create(dto); // id가 존재하는 경우 null return하도록 작성되어 있음

        // 비교
        assertEquals(expected, article);
    }

    @Test
    @Transactional // 조회가 아닌 생성, 변경, 삭제의 경우 Transaction으로 묶어서 Rollback할 수 있게 처리해줘야 한다.
    void update_success_1() { // update 메소드 성공 테스트 케이스 1 // 존재하는 id와 변경할 title, content만 있는 dto 입력
        // 예상
        Long id = 2L; // 대상 id
        String title = "AAAAAAAA"; // 변경할 title
        String content = "11111111"; // 변경할 content
        ArticleDto dto = new ArticleDto(null, title, content);
        Article expected = new Article(id, "AAAAAAAA", "11111111");

        // 실제
        Article article = articleService.update(id, dto);

        // 비교
        assertEquals(expected.toString(), article.toString());
    }

    @Test
    @Transactional // 조회가 아닌 생성, 변경, 삭제의 경우 Transaction으로 묶어서 Rollback할 수 있게 처리해줘야 한다.
    void update_success_2() { // update 메소드 성공 테스트 케이스 2 작성해보기
    }

    @Test
    @Transactional // 조회가 아닌 생성, 변경, 삭제의 경우 Transaction으로 묶어서 Rollback할 수 있게 처리해줘야 한다.
    void update_fail_1() { // update 메소드 실패 테스트 케이스 1 // 존재하지 않는 id와 변경할 title, content만 있는 dto 입력
        // 예상
        Long id = -1L; // 대상 id
        String title = "AAAAAAAA"; // 변경할 title
        String content = "11111111"; // 변경할 content
        ArticleDto dto = new ArticleDto(null, title, content);
        Article expected = null;

        // 실제
        Article article = articleService.update(id, dto); // id에 해당하는 엔티티가 없는 경우 null return하도록 작성되어 있음

        // 비교
        assertEquals(expected, article);
    }

    @Test
    @Transactional // 조회가 아닌 생성, 변경, 삭제의 경우 Transaction으로 묶어서 Rollback할 수 있게 처리해줘야 한다.
    void update_fail_2() { // update 메소드 실패 테스트 케이스 2 작성해보기
    }

    @Test
    @Transactional // 조회가 아닌 생성, 변경, 삭제의 경우 Transaction으로 묶어서 Rollback할 수 있게 처리해줘야 한다.
    void delete_success_1() { // delete 메소드 성공 테스트 케이스 1 // 존재하는 id 입력
        // 예상
        Long id = 2L;
        Article expected = new Article(id, "AAAA", "1111");

        // 실제
        Article article = articleService.delete(id);

        // 비교
        assertEquals(expected.toString(), article.toString());
    }

    @Test
    @Transactional // 조회가 아닌 생성, 변경, 삭제의 경우 Transaction으로 묶어서 Rollback할 수 있게 처리해줘야 한다.
    void delete_fail_1() { // delete 메소드 실패 테스트 케이스 1 // 존재하지 않는 id 입력
        // 예상
        Long id = -1L;
        Article expected = null;

        // 실제
        Article article = articleService.delete(id);

        // 비교
        assertEquals(expected, article);
    }
}

테스트 코드 작성 후 메소드 옆 재생 버튼 클릭 > Run ArticleServiceTest 클릭하면 해당 메소드의 테스트가 시작된다.

화면 좌측 하단 Show Passed, Show Ignored를 선택하고

메소드명 옆에 녹색 체크(테스트 정상) 또는 X 표시(테스트 실패)를 확인한다.

모든 메소드에 대해 테스트를 진행하고자 한다면 클래스명 옆에 있는 재생 버튼을 클릭하면 된다.

조회가 아닌 생성, 변경, 삭제 테스트의 경우

Transaction으로 묶어서 Rollback할 수 있게 처리해줘야 한다. (어노테이션 추가 @Transactional)

1. DTO + ApiController + Entity + Repository 구조 (Service 계층 없을 경우)

 

Client : 손님

RestController(Server) : 웨이터 & 셰프

Repository(Server) : 주방 보조

DataBase : 창고

 

src > main > java > com.example.firstproject > api의 ArticleApiController

package com.example.firstproject.api;

import com.example.firstproject.dto.ArticleDto;
import com.example.firstproject.entity.Article;
import com.example.firstproject.repository.ArticleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
public class ArticleApiController {

    // Service 계층 없이 구현했을 경우

    @Autowired
    private ArticleRepository articleRepository;

    // GET
    @GetMapping("/api/article")
    public List<Article> readAll() {
        return articleRepository.findAll(); // 전체 조회 후 Entity 반환
    }

    // GET
    @GetMapping("/api/article/{id}")
    public Article read(@PathVariable Long id) {
        return articleRepository.findById(id).orElse(null); // 조건부 조회 후 Entity 반환
    }

    // POST
    @PostMapping("/api/article")
    public Article create(@RequestBody ArticleDto dto) { // REST API의 경우 JSON으로 데이터 넘길 때 RequestBody를 써야 한다.
        Article article = dto.toEntity(); // 입력받은 DTO를 Entity로
        return articleRepository.save(article); // Entity 저장
    }

    // PATCH 또는 PUT
    @PatchMapping("/api/article/{id}")
    public ResponseEntity<Article> update(@PathVariable Long id, @RequestBody ArticleDto dto) {
        // 1: 수정용 엔티티 생성
        Article article = dto.toEntity(); // 입력받은 DTO를 Entity로
        // 2: 대상 엔티티를 조회
        Article target = articleRepository.findById(id).orElse(null); // 조건부 조회 후 Entity 반환
        // 3: 잘못된 요청 처리(대상이 없거나, id가 다른 경우)
        if (target == null || id != target.getId()) {
            // 400, 잘못된 요청 응답
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
        }
        // 4: 업데이트 및 정상 응답(200)
        target.patch(article); // 조건부 조회 Entity에 입력받은 값 적용
        Article updated = articleRepository.save(target); // Entity 저장
        return ResponseEntity.status(HttpStatus.OK).body(updated);
    }

    // DELETE
    @DeleteMapping("/api/article/{id}")
    public ResponseEntity<Article> delete(@PathVariable Long id) {
        // 1: 대상 찾기
        Article target = articleRepository.findById(id).orElse(null); // 조건부 조회 후 Entity 반환
        // 2: 잘못된 요청 처리
        if (target == null) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
        }
        // 3: 대상 삭제
        articleRepository.delete(target); // Entity 삭제
        return ResponseEntity.status(HttpStatus.OK).build();
    }
}

2. DTO + ApiController + Service + Entity + Repository 구조

일반적으로 Service의 업무처리가 Transaction 단위로 진행되기 때문에 Service 계층을 두고 역할을 나누도록 한다.

 

Client : 손님

RestController(Server) : 웨이터

Service(Server) : 셰프

Repository(Server) : 주방 보조

DataBase : 창고

 

src > main > java > com.example.firstproject > api의 ArticleApiController

package com.example.firstproject.api;

import com.example.firstproject.dto.ArticleDto;
import com.example.firstproject.entity.Article;
import com.example.firstproject.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
public class ArticleApiController {

    @Autowired // DI, 생성 객체를 가져와 연결
    private ArticleService articleService;

    @GetMapping("/api/article")
    public List<Article> readAll() { // 전체 조회
        return articleService.readAll();
    }

    @GetMapping("/api/article/{id}")
    public Article read(@PathVariable Long id) { // 조건부 조회
        return articleService.read(id);
    }

    @PostMapping("/api/article")
    public ResponseEntity<Article> create(@RequestBody ArticleDto dto) { // 추가 // REST API의 경우 JSON으로 데이터 넘길 때 RequestBody를 써야 한다.
        Article created = articleService.create(dto);
        return (created != null) ? ResponseEntity.status(HttpStatus.OK).body(created) : ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
    }

    @PatchMapping("/api/article/{id}")
    public ResponseEntity<Article> update(@PathVariable Long id, @RequestBody ArticleDto dto) { // 수정
        Article updated = articleService.update(id, dto);
        return (updated != null) ? ResponseEntity.status(HttpStatus.OK).body(updated) : ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
    }

    @DeleteMapping("/api/article/{id}")
    public ResponseEntity<Article> delete(@PathVariable Long id) { // 삭제
        Article deleted = articleService.delete(id);
        return (deleted != null) ? ResponseEntity.status(HttpStatus.NO_CONTENT).build() : ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
    }

    @PostMapping("/api/transaction-test")
    public ResponseEntity<List<Article>> transactionTest(@RequestBody List<ArticleDto> dtos) { // Transaction 실패 -> Rollback
        List<Article> createdList = articleService.createArticles(dtos);
        return (createdList != null) ? ResponseEntity.status(HttpStatus.OK).body(createdList) : ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
    }
}

src > main > java > com.example.firstproject > service의 ArticleService

package com.example.firstproject.service;

import com.example.firstproject.dto.ArticleDto;
import com.example.firstproject.entity.Article;
import com.example.firstproject.repository.ArticleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.stream.Collectors;

@Service // 서비스 선언! (서비스 객체를 Spring Boot에 생성)
public class ArticleService {

    @Autowired // DI(Dependency Injection)
    private ArticleRepository articleRepository;

    public List<Article> readAll() { // 전체 조회
        return articleRepository.findAll();
    }

    public Article read(Long id) { // 조건부 조회
        return articleRepository.findById(id).orElse(null);
    }

    public Article create(ArticleDto dto) { // 추가
        Article article = dto.toEntity();
        if (article.getId() != null) {
            return null;
        }
        return articleRepository.save(article);
    }

    public Article update(Long id, ArticleDto dto) { // 수정
        // 1: 수정용 엔티티 생성
        Article article = dto.toEntity(); // 입력받은 DTO를 Entity로
        // 2: 대상 엔티티를 조회
        Article target = articleRepository.findById(id).orElse(null); // 조건부 조회 후 Entity 반환
        // 3: 잘못된 요청 처리(대상이 없거나, id가 다른 경우)
        if (target == null || id != target.getId()) {
            // 400, 잘못된 요청 응답
            return null;
        }
        // 4: 업데이트 및 정상 응답(200)
        target.patch(article); // 조건부 조회 Entity에 입력받은 값 적용
        Article updated = articleRepository.save(target); // Entity 저장
        return updated;
    }

    public Article delete(Long id) { // 삭제
        // 1: 대상 찾기
        Article target = articleRepository.findById(id).orElse(null);
        // 2: 잘못된 요청 처리
        if (target == null) {
            return null;
        }
        // 3: 대상 삭제
        articleRepository.delete(target); // Entity 삭제
        return target;
    }

    @Transactional // 해당 메소드를 Transaction으로 묶는다. (해당 메소드 실행 중 실패 -> 이 메소드가 실행되기 전 상태로 Rollback)
    public List<Article> createArticles(List<ArticleDto> dtos) { // Transaction 테스트
        // 1: DTO 묶음을 Entity 묶음으로 변환
        List<Article> articleList = dtos.stream().map(dto -> dto.toEntity()).collect(Collectors.toList());
        // 2: Entity 묶음을 DB에 저장
        articleList.stream().forEach(article -> articleRepository.save(article));
        // 3: 강제 예외 발생
        articleRepository.findById(-1L).orElseThrow(
                () -> new IllegalArgumentException("결제 실패!")
        );
        // 4: 결과값 반환
        return articleList;
    }
}

src > main > java > com.example.firstproject > dto의 ArticleDto

package com.example.firstproject.dto;

import com.example.firstproject.entity.Article;
import lombok.AllArgsConstructor;
import lombok.ToString;

@AllArgsConstructor // Lombok 사용
@ToString // Lombok 사용
public class ArticleDto { // DTO 클래스

    private Long id;
    private String title;
    private String content;

//    public ArticleDto(Long id, String title, String content) { // @AllArgsConstructor와 같음
//        this.id = id;
//        this.title = title;
//        this.content = content;
//    }

//    @Override
//    public String toString() { // @ToString과 같음
//        return "ArticleDto{" +
//                "id=" + id +
//                ", title='" + title + '\'' +
//                ", content='" + content + '\'' +
//                '}';
//    }

    public Article toEntity() {
        return new Article(id, title, content);
    }
}

src > main > java > com.example.firstproject > entity의 Article

package com.example.firstproject.entity;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.ToString;
import javax.persistence.*;

@Entity // DB가 해당 객체를 인식 가능! (해당 클래스로 테이블 생성)
@NoArgsConstructor // Lombok 사용
@AllArgsConstructor // Lombok 사용
@ToString // Lombok 사용
@Getter // Lombok 사용
public class Article {

    @Id // 대표값을 지정! PK (EX : 주민등록번호)
    @GeneratedValue(strategy = GenerationType.IDENTITY) // 1, 2, 3,  ... DB가 id를 자동 채번하도록 하는 어노테이션 // JPA 버전 문제로 자동 채번이 안될 수 있다.
    private Long id;

    @Column
    private String title;

    @Column
    private String content;

//    public Article() { // Entity 기본 생성자 필요 // @NoArgsConstructor와 같음
//
//    }

//    public Article(Long id, String title, String content) { // @AllArgsConstructor와 같음
//        this.id = id;
//        this.title = title;
//        this.content = content;
//    }

//    @Override
//    public String toString() { // @ToString과 같음
//        return "Article{" +
//                "id=" + id +
//                ", title='" + title + '\'' +
//                ", content='" + content + '\'' +
//                '}';
//    }

//    // @Getter와 같음
//    public Long getId() {
//        return id;
//    }
//
//    public String getTitle() {
//        return title;
//    }
//
//    public String getContent() {
//        return content;
//    }

    public void patch(Article article) {
        if (article.title != null) {
            this.title = article.title;
        }

        if (article.content != null) {
            this.content = article.content;
        }
    }
}

src > main > java > com.example.firstproject > repository의 ArticleRepository

package com.example.firstproject.repository;

import com.example.firstproject.entity.Article;
import org.springframework.data.repository.CrudRepository;
import java.util.ArrayList;

public interface ArticleRepository extends CrudRepository<Article, Long> { // JPA가 제공 <관리대상 Entity, PK 타입>

    @Override
    ArrayList<Article> findAll(); // List 형태로 받기 위해 Override 했음
}

 

Postman을 사용한 API 테스트 화면

 

+ Recent posts