Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Autowire Interface with default implementation in Spring

I got an Interface with only one method that has default implementation

@Component
public interface ClockInterface {

    default Date currentDate() {
        return new Date();
    }
}

I want to inject that interface into some different service through it’s constructor like that

@Service
public class Service {
    
    private ClockInterface clock;

    public Service(ClockInterface clock) {
        this.clock = clock
    }
}

But on running the application I got the message

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Parameter 1 of constructor in com.api.app.application.Service required a bean of type 'constructor in com.api.app.application.ClockInterface' that could not be found.

Is there some elegant way to inject that Interface with all default implementation into a service?

I’ve tried to mark a ClockInterface as follow

@Component
@Primary
public interface ClockInterface {

    default Date currentDate() {
        return new Date();
    }
}

But it doesn’t change anything

>Solution :

The error is very obvious and pretty explanatory.

Field injection with interface only works when you have a class that implements that interface and a bean is available in the Spring container.

Introducing default method in the interface won’t help to make injection.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading