Skip to content
Advertisement

Is there a way to @Autowire non overridden methods?

I have an interface that is implemented by multiple classes, and these classes also have some extra methods. If I autowire the class. Is there a way I can autowire these extra methods?

Example-

Interface

public interface ExampleInterface {
    String methodOne();
    String methodTwo();
}

Service 1

@Service
public class ServiceOne implements ExampleInterface {

    @Override
    String methodOne() {
        return "one";
    }
    
    @Override
    String methodTwo() {
        return "two";
    }

    String methodThree() {
        return "three";
    }
}

Service 2

@Service
public class ServiceTwo implements ExampleInterface {

    @Override
    String methodOne() {
        return "1";
    }
    
    @Override
    String methodTwo() {
        return "2";
    }

    String otherMethod() {
        return "hello";
    }
}

If I try to directly Autowire the service like this-

@Service
public class Service{

    ServiceOne serviceOne;

    @Autowired
    public Service(ServiceOne serviceOne) {
        this.serviceOne = serviceOne;
    }
}

then I am getting error something like this-

Parameter 0 of constructor in Service required a bean of type 'ServiceOne' that could not be found.

Advertisement

Answer

I was using @ConditionalOnProperty on the services, that is why it was not getting autowired.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement