Bean에 관련된 내용

yshjft·2023년 1월 4일
0

Spring, JPA

목록 보기
10/16

@Autowired

방식

필드 주입

@Service
public class TestService {
	@Autowired
	private TestRepository testRepository;
}

수정자 주입

@Service
public class TestService {
    private TestRepository testRepository;

    @Autowired
    public void setTestRepository(TestRepository testRepository) {
        this.testRepository = testRepository
    }
 }

생성자 주입

@Service
public class TestService {
     private TestRepository testRepository;

     @Autowired
    public testService(TestRepository testRepository) {
        this.testRepository = testRepository;
    }
}

정리

  • 개발할 때 쓰고 있는 빈 주입 방법이 @Autowired이다.
  • @RequiredArugsConstructor(Lombok)를 사용하여 생성자 주입 시 @Autowired를 생략할 뿐이다.

참고

같은 이름의 Bean

  • Bean 오버라이딩 된다.(스프링 부트는 오버라이딩이 default는 아니다)
    • 자동 빈 VS 자동 빈
      • 예외 발생(ConflictingBeanDefinitionException)
    • 자동 빈 VS 수동 빈
      • 수동 빈이 우선권을 가진다.
    • (추가) 자동 빈 : by component scan
  • 현재 스프링 부트에서 빈 오버라이딩을 사용하려면 spring.main.allow-bean-definition-overriding = true로 설정해야 한다.
    • 어떤 놈이 오버라이드될지 예측하기 힘들다는데…

참고

profile
꾸준히 나아가자 🐢

0개의 댓글