Spring 중@Autowire 주입 에 대한 심도 있 는 설명

2287 단어 spring@autowire주입
spring 의@Autowire 가 속성 을 주입 할 때 유형 에 따라 주입 할 지 이름 에 따라 주입 할 지 고민 하고 있 습 니 다.오늘 테스트 를 써 서 증명 하 겠 습 니 다.
정의 인터페이스 TestService

public interface TestService {
 void test();
}
정의 인터페이스 구현:TestServiceImpl 1 과 TestServiceImpl 2

@Service
public class TestServiceImpl1 implements TestService {

 public void test() {
  System.out.println(1111);
 }
}

@Service
public class TestServiceImpl2 implements TestService {

 public void test() {
  System.out.println(2222);
 }
}
bean 의존 TestService 를 정의 합 니 다.

@Controller
public class TestController {
	//   beanBame=testService
 @Autowired
 TestService testService;

 public void test(){
  testService.test();
 }
}
테스트 클래스 작성:

@Configuration
@ComponentScan("test")
public class Test {
 public static void main(String[] args) {
  AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext();
  context.register(Test.class);
  context.refresh();
  TestService bean = context.getBean(TestService.class);
  bean.test();
 }
}
프로젝트 추적 원본 시작:spring 공장 에서 Bean 충전 속성 을 초기 화 할 때AbstractAutowireCapableBeanFactory.populateBean()방법 에서 백 엔 드 프로세서AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues() 를 실행 하고 계속 추적 합 니 다.DefaultListableBeanFactory.doResolveDependency()방법 에서findAutowireCandidates()유형 에 따라 두 Bean 에 일치 합 니 다.캡 처 참조:

가 져 온 Bean 이 두 개 를 초과 하기 때문에 spring 은 이름 에 따라 일치 합 니 다.일치 하 는 데 성공 하면 해당 하 는 bean 을 되 돌려 줍 니 다.일치 에 실패 하면 이상 을 던 집 니 다.그림:

지금까지 우 리 는@Autowire 주해 주입 속성의 원 리 를 발견 할 수 있 습 니 다.먼저 유형 에 따라 주입 하고 여러 개의 Bean 을 얻 으 면 이름 에 따라 일치 하 며 이름 이 일치 하지 않 으 면 이상 을 던 집 니 다.
총결산
Spring 중@Autowire 주입 에 관 한 이 글 은 여기까지 소개 되 었 습 니 다.더 많은 Spring 중@Autowire 주입 내용 은 예전 의 글 을 검색 하거나 아래 의 관련 글 을 계속 찾 아 보 세 요.앞으로 많은 응원 부 탁 드 리 겠 습 니 다!

좋은 웹페이지 즐겨찾기