[Spring] 스프링 빈 등록과 의존관계

2024. 12. 19. 22:56·Spring

스프링 빈 등록


컴포넌트 스캔과 자동 의존관계 설정


1. @SpringBootApplication 클래스 시작될 때 Spring 컨테이너(ApplicationContext) 통 생성(초기화)

2.모든 @Component 계열(@Controller, @Service, @Repository) 클래스들 객체(Bean) 생성해  스프링 컨테이너에 등록

(이 객체 스프링이 관리) (by.@SpringBootApplication 클래스의 @ComponentScan)

3. @Autowired 통해 의존성 주입

->> 스프링 컨테이너에서 스트링 빈이 관리됨

 

*빈(Bean): 스프링 컨테이너에 의해 관리되는 객체

 

 

 

 @Controller //1.MemberController객체 컨테이너에 생성
 public class MemberController {
 
     //private final MemberService memberService = new MemberService();
     //New가 아니라 공용으로 쓰기위해 스프링컨테이너에 등록(@Autowired)해 받아써야함
     private final MemberService memberService;

     @Autowired //연관 객체(MemberService) 찾아 연결(객체 의존관계를 외부에서 넣어주는 것: DI.의존성 주입)
     public MemberController(MemberService memberService) { //⌘N, 생성자
         this.memberService = memberService;
     }
}

@Service //1. MemberService 빈 등록
public class MemberService {
	private final MemberRepository memberRepository;

    @Autowired
    public MemberService (MemberRepository memberRepository) {
        this.memberRepository = memberRepository;
    }
    ....

 

 

참고. 스프링 컨테이너에 스프링 빈을 등록할 때 , 기본으로 싱글톤으로 등록

*싱글톤?

하나의 클래스에 대해 단 하나의 객체(인스턴스)만 생성해서 공유

(ex. MemberController는 MemberController하나만)

 

 

코드로 직접 빈 등록


@Controller는 두고 나머지는 제거

package hello.hellospring;

import hello.hello_spring.repository.MemberRepository;
import hello.hello_spring.repository.MemoryMemberRepository;
import hello.hello_spring.service.MemberService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration//설정파일이다(Spring 컨테이너가 초기화될 때 실행)
public class SpringConfig {
    @Bean //빈이름 메서드명, 반환 객체 빈등록
    public MemberService memberService() { //
    	return new MemberService(memberRepository());
    }
    @Bean
    public MemberRepository memberRepository() {
    	return new MemoryMemberRepository();
    }
}

'Spring' 카테고리의 다른 글

[Spring] AOP(Aspect-Oriented Programming)  (0) 2025.01.22
[Spring] 스프링 DB 접근(JDBC,JdbcTemplate,JPA,스프링 데이터 JPA)  (0) 2025.01.12
[Spring] From 입력, 조회  (0) 2024.12.22
[Spring] 웹 계층 구조, Test  (0) 2024.12.17
[Spring] 클라이언트-서버 통신 방식  (0) 2024.12.10
'Spring' 카테고리의 다른 글
  • [Spring] 스프링 DB 접근(JDBC,JdbcTemplate,JPA,스프링 데이터 JPA)
  • [Spring] From 입력, 조회
  • [Spring] 웹 계층 구조, Test
  • [Spring] 클라이언트-서버 통신 방식
Naah
Naah
  • Naah
    blueprint
    Naah
  • 전체
    오늘
    어제
    • 분류 전체보기 (106)
      • Java (28)
      • Kotlin (0)
      • TypeScript (7)
      • React (22)
      • Next.js (1)
      • Spring (22)
      • JPA (12)
      • Spring Data JPA (6)
      • Querydsl (1)
      • Error (7)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
    • 글쓰기
    • manage
  • 링크

  • 공지사항

  • 인기 글

  • 태그

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Naah
[Spring] 스프링 빈 등록과 의존관계
상단으로

티스토리툴바