programing

스프링: 구현된 클래스가 아닌 인터페이스를 자동 배선하는 이유는 무엇입니까?

prostudy 2022. 7. 5. 22:07
반응형

스프링: 구현된 클래스가 아닌 인터페이스를 자동 배선하는 이유는 무엇입니까?

interface IA
{
  public void someFunction();
}

@Resource(name="b")
class B implements IA
{
  public void someFunction()
  {
    //busy code block
  }
  public void someBfunc()
  {
     //doing b things
  }
}

@Resource(name="c")
class C implements IA
{
  public void someFunction()
  {
    //busy code block
  }
  public void someCfunc()
  {
     //doing C things
  }
}

class MyRunner
{

  @Autowire
  @Qualifier("b") 
  IA worker;

  worker.someFunction();
}

누가 나한테 설명 좀 해줄래?

  • 봄은 어떤 다형형을 사용해야 하는지 어떻게 아는가?
  • 필요합니까?@Qualifier또는@Resource?
  • 구현된 클래스가 아닌 인터페이스를 자동 배선하는 이유는 무엇입니까?

봄은 어떤 다형형을 사용해야 하는지 어떻게 아는가?

인터페이스의 구현이 1개뿐이고 그 구현에 주석이 붙어 있는 한@Component스프링의 컴포넌트 스캔을 활성화하면 스프링 프레임워크는 (인터페이스, 구현) 쌍을 찾을 수 있습니다.컴포넌트 스캔이 활성화되지 않은 경우 application-config.xml(또는 동등한 스프링 구성 파일)에서 bean을 명시적으로 정의해야 합니다.

@Qualifier 또는 @Resource 중 어느 것이 필요합니까?

여러 구현이 완료되면 각 구현을 검증해야 합니다.또한 자동 배선 중에는@Qualifier적절한 구현을 주입하기 위한 주석과 함께@Autowired주석입니다.@Resource(J2EE 시멘틱스)를 사용하고 있는 경우는, 다음의 명령어를 사용해 빈 이름을 지정할 필요가 있습니다.name이 주석의 속성.

구현된 클래스가 아닌 인터페이스를 자동 배선하는 이유는 무엇입니까?

우선, 인터페이스 전반을 코드화하는 것은 항상 좋은 방법입니다.둘째, 봄의 경우 실행 시 어떤 구현이든 삽입할 수 있습니다.일반적인 사용 사례는 테스트 단계에서 모의 구현을 주입하는 것입니다.

interface IA
{
  public void someFunction();
}


class B implements IA
{
  public void someFunction()
  {
    //busy code block
  }
  public void someBfunc()
  {
     //doing b things
  }
}


class C implements IA
{
  public void someFunction()
  {
    //busy code block
  }
  public void someCfunc()
  {
     //doing C things
  }
}

class MyRunner
{
     @Autowire
     @Qualifier("b") 
     IA worker;

     ....
     worker.someFunction();
}

bean 설정은 다음과 같습니다.

<bean id="b" class="B" />
<bean id="c" class="C" />
<bean id="runner" class="MyRunner" />

또는 컴포넌트 스캔이 존재하는 패키지에서 컴포넌트 스캔을 유효하게 했을 경우는, 각 클래스의 수식을 실시할 필요가 있습니다.@Component다음과 같습니다.

interface IA
{
  public void someFunction();
}

@Component(value="b")
class B implements IA
{
  public void someFunction()
  {
    //busy code block
  }
  public void someBfunc()
  {
     //doing b things
  }
}


@Component(value="c")
class C implements IA
{
  public void someFunction()
  {
    //busy code block
  }
  public void someCfunc()
  {
     //doing C things
  }
}

@Component    
class MyRunner
{
     @Autowire
     @Qualifier("b") 
     IA worker;

     ....
     worker.someFunction();
}

그리고나서workerMyRunner유형의 인스턴스가 주입됩니다.B.

또한 Cglib2AopProxy Unable to proxy 메서드와 같은 로그에서 몇 가지 경고가 발생할 수 있습니다. 밖에 많은 이유가 여기에 설명되어 있습니다.왜 항상 단일 구현 인터페이스가 서비스 dao 계층에 있습니까?

following bean in my following bean in my following bean.@Autowired포스트 프로세스이므로 XML 구성 파일

<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"></bean>

언급URL : https://stackoverflow.com/questions/12899372/spring-why-do-we-autowire-the-interface-and-not-the-implemented-class

반응형