Issue
In my Spring Boot 2.0.2 application I am trying to inject a component herited from abstract class which implements an interface and it doesn't work.
Code :
Component Abstract : (Do I need to put @Component ?)
package app.project.service;
@Component
public abstract class AbstractStepService implements IStepService {
protected final void addTask() {
...
}
@Override
public StepDataDto launch() throws StepException {
...
}
}
Interface :
package app.project.service;
public interface IStepService {
StepDataDto launch() throws StepException;
}
package app.project.service;
Component :
@Component
public class CStepServiceImpl extends AbstractStepService implements IStepService {
@PostConstruct
private void defineTasks() {
}
}
package app.project.service;
Junit Test :
@RunWith(SpringRunner.class)
@SpringBootTest
public class CStepServiceTest {
@Autowired
@Qualifier("cStepServiceImpl")
private IStepService service;
}
package app.project;
Application :
@SpringBootApplication
@ComponentScan(basePackages ={"app.project.service"})
public class MyApplication {}
Error message when launching my Junit test :
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'app.project.service.IStepService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=cStepServiceImpl)}
Any idea ?
Thanks
Solution
Change your declaration like this
@Autowired
@Qualifier("CStepServiceImpl")
private IStepService service;
or
@Autowired
private IStepService CStepServiceImpl;
That should work. The bean name created automatically by spring has CStepServiceImpl name.
You can also name your bean like this
@Component(value = "myName")
public class CStepServiceImpl extends AbstractStepService implements IStepService {
}
and use myName during Autowiring.
Answered By - pvpkiran