복붙노트

[SPRING] 인터페이스는 IoC / DI의 @Component 주석으로 주석 처리됩니다. 그 이유는 무엇일까요?

SPRING

인터페이스는 IoC / DI의 @Component 주석으로 주석 처리됩니다. 그 이유는 무엇일까요?

어떤 때는 인터페이스가 @Component 주석으로 주석 처리됩니다. 그렇다면이 인터페이스를 구현하는 클래스가 컴포넌트로 취급 될 것이라는 것이 분명한 이유입니다. 그러나 내가 옳다면 그건 사실이 아닙니다.

그렇다면 인터페이스에서 @Component 어노테이션의 목적은 무엇입니까?

해결법

  1. ==============================

    1.@Component를 사용하여 인터페이스에 주석을다는 것은 Spring 클래스, 특히 일부 Spring 스테레오 타입 주석에 공통적이다.

    @Component를 사용하여 인터페이스에 주석을다는 것은 Spring 클래스, 특히 일부 Spring 스테레오 타입 주석에 공통적이다.

    package org.springframework.stereotype;
    ...
    @Component
    public @interface Service {...}
    

    또는 :

    package org.springframework.boot.test.context;
    ...
    @Component
    public @interface TestComponent {...}
    

    @Component가 상속 된 주석으로 선언되지 않았습니다.

    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface Component {...}
    

    그러나 컨텍스트 로딩 중에 Spring은 후보 클래스에서 선언 된 주석의 계층을 고려하여 빈을 찾습니다.

    기본 소스에서 bean 정의를로드하는 org.springframework.boot.BeanDefinitionLoader 클래스 (Spring Boot 의존성에 포함됨)에서 다음의 예제를 볼 수있다. org.springframework.core.annotation.AnnotationUtils.findAnnotation () Spring은 주석의 전체 계층에서 주석을 검색하는 데 사용합니다.

    class BeanDefinitionLoader {
     ...
     private boolean isComponent(Class<?> type) {
        // This has to be a bit of a guess. The only way to be sure that this type is
        // eligible is to make a bean definition out of it and try to instantiate it.
        if (AnnotationUtils.findAnnotation(type, Component.class) != null) {
            return true;
        }
        // Nested anonymous classes are not eligible for registration, nor are groovy
        // closures
        if (type.getName().matches(".*\\$_.*closure.*") || type.isAnonymousClass()
                || type.getConstructors() == null || type.getConstructors().length == 0) {
            return false;
        }
        return true;
     }
     ...
    }
    

    구체적으로 @Service 주석 자체는 @Component로 주석 처리되므로 Spring은 @Service로 주석 처리 된 후보 클래스를 인스턴스화 할 Bean으로 간주합니다.

    그래서 추측은 맞습니다.

    하지만 이것은 자바 인터페이스 인 인터페이스 (예 : @Service)에서만 작동하며 일반 인터페이스에서는 작동하지 않습니다.

    Spring 클래스의 경우,이 방법은 실제의 스테레오 타입을 풍부하게하지만 자신 만의 bean을 위해, 구현보다는 인터페이스를 위해 @Component를 사용하는 것이 효과적이지 않고 이점보다 많은 단점을 가져올 수있다.

  2. ==============================

    2.그렇다고해서 인터페이스에 @component를 추가 할 필요가 없다. bean을위한 참조를 만들 수 없으므로 bean이 아니기 때문이다. 주요 부분은 실제로 당신이 어디에 의존성을 주입하는지에 대한 @autowired입니다. 예를 들어

    그렇다고해서 인터페이스에 @component를 추가 할 필요가 없다. bean을위한 참조를 만들 수 없으므로 bean이 아니기 때문이다. 주요 부분은 실제로 당신이 어디에 의존성을 주입하는지에 대한 @autowired입니다. 예를 들어

    공용 인터페이스 SortAlog (); 공용 클래스 BubbleSortAlgo ();

    아니 우리는 동적 바인딩을 따르고 인터페이스의 객체를 만들고 있지만 구현은 런타임에 있습니다.

    그러므로 @autowired는 내부적으로 객체를 생성 할 것이고 우리는 bubbleSortAlgo를위한 @component와 주입을위한 유일한 후보자를 가지고 있으므로 거기에서 참조를 얻을 것입니다.

    나는 여기서 한 가지 강조 할 수 있었으면 좋겠다.

  3. from https://stackoverflow.com/questions/46502450/interfaces-are-annotated-with-component-annotation-in-spring-ioc-di-what-could by cc-by-sa and MIT license