2026-02-05
Spring
스프링
Java로 웹 서버(API 서버) 쉽게 만드는 프레임워크
스프링 전체 구조
Controller → Service → Repository → DB
위 흐름에서 데이터 객체 2개 존재
DTO (프론트용)
Entity (DB용)
프론트 요청
→ Controller
→ Service
→ Repository
→ DB
(→ Entity 반환)
(→ Service에서 DTO 변환)
→ 다시 Controller
→ 프론트 응답 (DTO)
Controller
프론트 요청 받는 곳
@RestController
@RequestMapping("/user")
public class UserController {
@GetMapping("/1")
public String getUser() {
return"user";
}
}
브라우저:
GET/user/1
역할:
- 요청 받기
- json 반환
- service 호출
⇒ 프론트 axios랑 연결되는 지점
Service
실제 로직 처리
@Service
public class UserService {
public String getUser() {
return"user data";
}
}
- 계산
- 비즈니스 로직
- 조건 처리
- 여러 repository 조합
- Controller는 Service 호출만 함
- Entity → DTO 변환
Repository (DB 연결)
DB 접근 담당
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
- DB 조회
- 저장
- 수정
- 삭제
- SQL 직접 안 써도 됨 (JPA)
Entity (DB 테이블)
테이블 = 클래스
@Entity
publicclassUser {
@Id
private Long id;
private String name;
}
DB 테이블:
usertable
id |name
전체 흐름 예시 (로그인)
프론트에서 로그인 요청
POST /login
흐름:
Controller
→ login 요청 받음
Service
→id/pw 검증
Repository
→ DB 조회
Service
→ JWT 생성
Controller
→ 토큰 반환
프론트
→ 저장
스프링 핵심 개념
-
DI (의존성 주입)
자동 연결, new 안 써도 됨.
@RequiredArgsConstructor publicclassUserController { privatefinal UserService userService; } -
Bean
스프링이 관리하는 객체, 붙으면 자동 관리됨
@Controller @Service @Repository -
MVC 패턴
Controller → Service →Model(Entity) →View(json)프론트 없는 서버는 View 대신 JSON
-
REST API
URL 설계 방식
GET /users GET /users/1 POST /users PUT /users/1 DELETE /users/1 -
JPA (DB 연결)
SQL 대신 객체로 DB 사용
userRepository.findById(1); userRepository.save(user); -
Spring Boot
스프링 쉽게 실행하는 버전
Spring = 설정 지옥 (요즘은 거의 Boot만 씀) SpringBoot= 바로 실행
프로젝트 폴더 구조
src/main/java
├ controller
├ service
├ repository
├ entity
├ dto
└ config