애플리케이션에서 DB에 연동하여 메모리가 아닌 DB에 쿼리를 날리는 것(JDBC) → 20년 전 방식
package hello.hello_spring;
import hello.hello_spring.repository.JdbcMemberRepository;
import hello.hello_spring.repository.MemberRepository;
import hello.hello_spring.repository.MemoryMemberRepository;
import hello.hello_spring.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
@Configuration
public class SpringConfig {
private DataSource dataSource;
@Autowired
public SpringConfig(DataSource datasource){
this.dataSource = datasource;
}
@Bean
public MemberService memberService(){
return new MemberService(memberRepository());
}
@Bean
MemberRepository memberRepository(){
// return new MemoryMemberRepository();
return new JdbcMemberRepository(dataSource);
}
}
우리가 스프링을 왜 사용할까?
왜 객체지향적인 설계가 좋은 이유는, '다형성을 활용'하기 때문에 인터페이스를 두고 구현체 바꿔끼기를 할 수 있다.
스프링은 이걸 매우 편리하게 구현할 수 있도록 컨테이너가 지원해준다. Dependency Injection 덕분에 매우 편리하게 개발할 수 있다.
MemeberService는 MemberRepository에 의존하고 있고,
MemberRepository는 구현체로 MemoryMemberRepository와 JdbcMemberRepository가 있다.
기존에는 메모리 버전의 스프링빈으로 등록했다면,
이제는 얘를 빼고 jdbc 버전의 repository를 등록하면 이제 구현체가 jdbc 버전으로 바뀌어 DB로 돌아간다.
이걸 'SOLID 단일 원칙'이라고 부른다.
✏️ SOLID 객체지향 프로그래밍의 5가지 원칙
SOLID 원칙(객체지향 설계 원칙)1. SPR(Single Responsibility): 단일 책임 원칙클래스는 단 한 개의 책임(=기능)을 가져야 함한 클래스가 수행할 수 있는 기능이 여러 개면 안됨책임을 분리해서 한 개만 가
dropdew.tistory.com
이중 가장 중요한 것은, '개방, 폐쇄 원칙 OCP(Open-Closed Principle)'이라고 한다.
확장에는 열려있고, 수정 변경에는 닫혀있다.
객체지향에서 말하는 다형성이라는 개념을 잘 활용하면 기능을 완전히 변경해도, 애플리케이션 전체를 수정할 필요는 없다.
하지만, 조립하는 코드는 수정할 필요가 있음(여기서는 jdbc 버전의 memberRepository)
그래도 실제 어플리케이션 돌아가는데 필요한 코드들은 변경하지 않아도 됨
jdbc기반의 memberRepository를 생성했지만, 기존 코드들은 전혀 변경하지 않음
→ 이게 바로 개방, 폐쇄 원칙인 OOP가 지켜진 것
스프링의 DI(Dependencies Injection)를 사용하면 '기존 코드를 전혀 손대지 않고, 설정만으로 구현 클래스를 변경할 수 있다.
→ 데이터를 DB에 저장하므로 스프링 서버를 다시 실행해도 데이터가 안전하게 저장된다.
'Backend > Spring 입문' 카테고리의 다른 글
[Spring] 5. 회원관리 예제(웹 MVC 개발) (1) | 2025.04.29 |
---|---|
[Spring] 4. 스프링 빈과 의존관계 (1) | 2025.04.29 |
[Spring] 3. 회원 관리 예제 - 회원 레포지토리 테스트 케이스 작성 / 서비스 개발 / 서비스 테스트 (0) | 2025.04.25 |
[Spring] 3. 회원 관리 예제 - 비즈니스 요구사항 정리 / 회원 도메인과 레포지토리 생성 (1) | 2025.04.19 |
[Spring] 2. 스프링 웹 개발 기초 (0) | 2025.04.19 |