So I'm trying to autowire an interface.
MyApp:
@SpringBootApplication(scanBasePackages={"com.B","com.C"})
public class MyApp {
...
}
MyController (which is in package com.B):
@RestController
@RequestMapping("/users")
public class UserController
{
@Autowired
MyInterface myInterface;
}
MyInterface (which is in package com.C):
@Service
public interface MyInterface
{
...
}
But I'm getting this error:
Consider defining a bean of type 'C.MyInterface' in your configuration.
even though I have:
- The package included here:
@SpringBootApplication(scanBasePackages={"com.B","com.C"})
@Service
in the interface
Is it even possible to autowire an interface?
CodePudding user response:
Yes you can inject an interface. But there should be at least one implementation that is declared as bean, so Spring manages it and will know what to inject. If you have more then one implementation you will need to specify which one you want. Read about annotation @Resource
and about and it's property "name". A good article to read about it would be Wiring in Spring: @Autowired, @Resource and @Inject. Also, If you have many implementations of the same interface and want to inject them all you can do this:
@Autowired
private List<DataSource> dataSources;
If DataSource
is an interface the list will contain all of its implementations. You can read about it here and here