[Spring] 빈 생명주기 콜백
·
Spring
빈 생명주기 콜백스프링에서 빈(Bean)의 생성부터 소멸까지 특정 동작을 수행하는 방법을 제공하는 기능 ex. 데이터베이스 커넥션 풀이나, 네트워크 소켓처럼 애플리케이션 시작 시점에 미리 필요한 연결을 해두고,애플리케이션 종료 시점에 연결을 모두 종료하는 작업을 진행하려면, 객체의 초기화와 종료 작업이 필요 빈 생명주기(Lifecycle)스프링 컨테이너 생성 > 스프링 빈 생성 > 의존관계 주입 > 초기화 콜백 > 빈 사용 > 소멸전 콜백(컨테이너에서 제거) > 스프링 종료 *초기화 콜백: 빈이 생성되고, 빈의 의존관계 주입이 완료된 후 호출 소멸전 콜백: 빈이 소멸되기 직전에 호출 참고 : 객체를 생성하는 부분과 초기화 하는 부분을 명확하게 나누는 것이 유지보수 관점에서 좋음 빈 생명주기 콜백 구현1...
[Spring] 의존관계 자동 주입
·
Spring
의존관계 주입1. 생성자 주입 (권장)생성자 생성 시점 딱 1번 호출불변,필수 의존관계에 사용@Servicepublic class MemberServiceImpl implements MemberService { /////필수,불변 private final MemberRepository memberRepository; @Autowired //MemberRepository타입찾아 주입 public MemberServiceImpl(MemberRepository memberRepository) { this.memberRepository = memberRepository; }*생성자가 딱 1개라면 @Autowired 생략 가능 권장이유 ..
[Spring] 컴포넌트 스캔
·
Spring
컴포넌트 스캔과 의존관계 자동 주입설정 정보없이 자동 스프링 빈 등록하는 @ComponentScan(어노테이션 붙은 클래스찾아 빈등록)의존관계도 자동으로 주입하는 @Autowired -@Bean 사용직접 설정정보,의존관계 명시@Beanpublic MemberService memberService() { return new MemberServiceImpl(memberRepository());}-@ComponentScan + @Autowired 사용@Servicepublic class MemberServiceImpl implements MemberService { private final MemberRepository memberRepository; @Autowired //MemberRepository..
[Spring] 싱글톤 컨테이너
·
Spring
싱글톤 탄생 배경과 필요성여러 고객이 동시에 요청 시public class SingletonTest { @Test @DisplayName("스프링 없는 순수한 DI 컨테이너") void pureContainer() { AppConfig appConfig = new AppConfig(); //1. 조회: 호출할 때 마다 객체를 생성 MemberService memberService1 = appConfig.memberService(); //2. 조회: 호출할 때 마다 객체를 생성 MemberService memberService2 = appConfig.memberService(); //참조..
[Spring] 스프링 컨테이너와 스프링 빈 조회
·
Spring
스프링 컨테이너생성ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class); ApplicationContext 를 스프링 컨테이너라 함 (인터페이스)AnnotationConfigApplicationContext(AppConfig.class)는 ApplicationContext` 인터페이스의 구현체 과정1. new AnnotationConfigApplicationContext(AppConfig.class) 설정 정보줌2. 스프링 컨테이너(DI 컨테이너) 생성3. AppConfig.class 기반 객체 생성, 빈등록, 의존관계 주입 * 빈이름 직접 부여도 가능(대신 중복x)@Bean(nam..
[Spring] 스프링 개요, SOLID, DI 컨테이너 💡
·
Spring
스프링이란다양한 기술(부트, 시큐리티, 클라우드, 배치 등)을 포함한 Java 기반 애플리케이션 프레임워크 -스프링 프레임워크• 핵심 기술: 스프링 DI 컨테이너, AOP, 이벤트, 기타• 웹 기술: 스프링 MVC, 스프링 WebFlux• 데이터 접근 기술: 트랜잭션, JDBC, ORM 지원, XML 지원• 기술 통합: 캐시, 이메일, 원격접근, 스케줄링• 테스트: 스프링 기반 테스트 지원• 언어: 코틀린, 그루비 스프링 부트 통해 스프링 프레임워크기술 편리하게 사용 -스프링 부트스프링을 편리하게 사용할 수 있도록 지원하며,내장 웹 서버(Tomcat 등) 포함, 자동 구성, 간결한 설정, 프로덕션 기능(메트릭, 상태 확인 등)을 제공하여단독 실행 가능한 스프링 애플리케이션을 쉽게 생성 또한,자바의 큰 ..
[Spring] AOP(Aspect-Oriented Programming)
·
Spring
AOP(Aspect-Oriented Programming) 공통 관심 사항을 분리하여 핵심 비즈니스 로직과 독립적으로 관리할 수 있게 하는 프로그래밍 기법 필요 상황모든 메소드의 호출 시간 측정하고 싶을 때회원 가입 시간, 회원 조회 시간을 측정하고 싶을 때(핵심 관심 사항x)공통 관심 사항(cross-cutting concern) vs 핵심 관심 사항(core concern)  > 시간 측정 로직은 공통 관심 사항으로, 핵심 비즈니스 로직과 분리하는 것이 유지보수 좋음> 시간 측정 로직이 핵심 로직과 섞이면 수정이 어렵고, 변경 시 모든 코드를 찾아 수정해야 하는 문제 발생 적용 -시간 측정 AOP 등록@Component@Aspect //AOPpublic class TimeTraceAop { @A..
[Spring] 스프링 DB 접근(JDBC,JdbcTemplate,JPA,스프링 데이터 JPA)
·
Spring
H2 데이터베이스개발이나 테스트 용도로 가볍고 편리한 DB, 웹 화면 제공 (실무에선 MySQL, Oracle 많이씀)설치> https://www.h2database.com H2 Database Engine (redirect)H2 Database Engine Welcome to H2, the free SQL database. The main feature of H2 are: It is free to use for everybody, source code is included Written in Java, but also available as native executable JDBC and (partial) ODBC API Embedded and client/server mowww.h2database.c..
[Spring] From 입력, 조회
·
Spring
From 입력-MemberController@GetMapping(value = "/members/new")public String createForm() { return "members/createMemberForm";}@PostMapping("/members/new")public String create(MemberForm form) { Member member = new Member(); member.setName(form.getName()); memberService.join(member); return "redirect:/"; //루트("/") 페이지로 이동} -createMemberForm.html 이름 //name 서버넘어올때 키값 ..
[Spring] 스프링 빈 등록과 의존관계
·
Spring
스프링 빈 등록컴포넌트 스캔과 자동 의존관계 설정1. @SpringBootApplication 클래스 시작될 때 Spring 컨테이너(ApplicationContext) 통 생성(초기화)2.모든 @Component 계열(@Controller, @Service, @Repository) 클래스들 객체(Bean) 생성해 스프링 컨테이너에 등록(이 객체 스프링이 관리) (by.@SpringBootApplication 클래스의 @ComponentScan)3. @Autowired 통해 의존성 주입->> 스프링 컨테이너에서 스트링 빈이 관리됨 *빈(Bean): 스프링 컨테이너에 의해 관리되는 객체 @Controller //1.MemberController객체 컨테이너에 생성 public class Member..