Using the @Autowired Field in a Component Implementing the Same Interface

Can I be sure that the delegate field in the SomeInterfaceAdvancedImpl class (see code below) will always be of type SomeInterfaceBasicImpl. I just checked the type in the debugger and it worked, but I have doubts that it will always work the same way. Can someone explain this phenomenon (why does it work)?

public interface SomeInterface {
    long doSomething(String param);
}

public abstract class SomeInterfaceAbstractImpl implements SomeInterface {
    public abstract long doSomething();
}

@Component
class SomeInterfaceBasicImpl extends SomeInterfaceAbstractImpl {
    @Override
    public long doSomething(String param) {
      return 1;
    };
}

@Primary
@Component
class SomeInterfaceAdvancedImpl extends SomeInterfaceAbstractImpl {

    @Autowired
    SomeInterface delegate;

    @Override
    public long doSomething(String param) {
      if (param == "2") {
        return 2;
      } else {
        return delegate.doSomething(param);
      }
    };
}

      

+3


source to share


1 answer


Add another implementation SomeInterface

and you will see a Spring thrown error NoSuchBeanDefinitionException

. In this case, you need to use annotation @Qualifier

to tell Spring which bean to use.



See the link on mkyong.com for a better understanding.

+1


source







All Articles