Bean cannot be found unless it is in upper package

44 Views Asked by At

I have a temporal activity class under package

com.x.nl.y.customercare.processes.activity.subscription

Class looks like

@Slf4j
@AllArgsConstructor
@Component
public class ServiceActivitiesImpl implements ServiceActivities {
    private final Service service;

    @Override
    public canBeSavedResponse canBeSaved(CanBeSavedRequest request) {
        return service.canBeSaved(request);
    }
}

The injected Service bean class is under the package

com.x.nl.y.customercare.service

The issue is Spring cannot inject this service bean into activity due to

org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.x.nl.y.customercare.service.Service' 

But if I move it into com.x.nl.y.customercare.processes or any subpackage of it then it works.

What's wrong with the service package ?

2

There are 2 best solutions below

0
On

Seems to me this is an due to incorrect component scanning. Your application is only scanning beans defined in com.x.nl.y.customercare.processes package.

Make sure that @ComponentScan or @SpringBootApplication annotation on you main application class includes the package com.x.nl.y.customercare.service as well, otherwise spring won't detect it.

@ComponentScan(
    basePackages = {
        "com.x.nl.y.customercare.processes",
        "com.x.nl.y.customercare.service"
    }
)

or using @SpringBootApplication

@SpringBootApplication(
    scanBasePackages = {
        "com.x.nl.y.customercare.processes",
        "com.x.nl.y.customercare.service"
    }
)

or you can simply put com.x.nl.y.customercare to include both the packages.

This can also occur if your main application class is under com.x.nl.y.customercare.processes package which by default only scan packages within processes for any bean definitions.

2
On

are you missing @Autowired ? spring scans packages looking for specific annotations. maybe the service is in a package out of the default scope