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
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
4
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.
I’ve just added simple configuration for that interface
@Configuration
public class ClockConfig {
@Bean
public ClockInterface clock() {
return new ClockInterface() {};
}
}