Spring

스프링 빈과 의존관계

Hasky96 2022. 9. 4. 22:01
  • @Autowired :  여러번 생성될 필요가 없는 객체들을 스프링컨테이너에서 가져와 연결해 줌. new 생성자를 통해 중복 생성되는 것을 방지. 
    • @Component, @Service, @Repository annotation을 추가해 두어야  Component Scan으로 스프링컨테이너에 추가됨.(스프링 빈으로 등록)
    • @SpringBootApplication이 작성된 패키지 하위만 컴포넌트 스캔이 일어남(default)
    • 스프링 빈으로 등록될때는 항상 싱글톤으로 등록된다.(default)
  • 직접 설정파일에서 Spring Bean으로 등록하기
    • SpringConfigure
@Configuration
public class SpringConfig{
	
    @Bean
    public TestService testService(){// testRepository 의존
    	return new TestService(testRepository());
    }
    
    @Bean
    public TestRepository testRepository(){
    	return new TestRepositoryImpl(); // => 구현체 반환
    }
    
}

 

  • DI(Dependency Injection)
    • 생성자
    • Autowired => field 주입
    • Setter 주입