Aleksey Timohin
Aleksey Timohin

Reputation: 621

Using @Autowired field in component implementing the same interface

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

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);
      }
    };
}

Upvotes: 3

Views: 821

Answers (1)

shx
shx

Reputation: 1138

Add some other implementation of SomeInterface and you'll see the Spring error caused by NoSuchBeanDefinitionException. In that case you'll need to use @Qualifier annotation to tell Spring which bean to use.

See this link at mkyong.com for better understanding.

Upvotes: 1

Related Questions