Spring Boot - Can't handle IllegalStateException - spring-boot

I am in the process of learning spring boot, however, I encountered a problem and I can not find a solution. When I try to run the test, I get the following exception.
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'bookServiceImplementation' defined in file []: Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'uploadFileServiceImplementation' defined in file []: Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.modelmapper.ModelMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'uploadFileServiceImplementation' defined in file []: Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.modelmapper.ModelMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.modelmapper.ModelMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
I tried to put an annotation in different places, but it did not solve my problem. I completely don't know how should I create ModelMapper bean. Maybe you will know how to deal with it. Here is my code:
BookServiceImplementation.class
#Service
public class BookServiceImplementation implements BookService {
private BookRepository bookRepository;
private UploadFileService uploadFileService;
private ModelMapper modelMapper;
#Autowired
public BookServiceImplementation(BookRepository bookRepository, UploadFileService uploadFileService,
ModelMapper modelMapper){
this.bookRepository = bookRepository;
this.uploadFileService = uploadFileService;
this.modelMapper = modelMapper;
}
#Override
public void addBook(AddBookResource addBookResource) {
Book book = new Book();
Long coverImageId = addBookResource.getCoverImageId();
Long contentId = addBookResource.getContentId();
UploadFile coverImage = null;
UploadFile bookContent = null;
if (coverImage != null){
coverImage = uploadFileService.findById(coverImageId)
.map(fileResource -> modelMapper.map(fileResource, UploadFile.class))
.orElse(null);
}
if (contentId != null){
bookContent = uploadFileService.findById(contentId)
.map(fileResource -> modelMapper.map(fileResource, UploadFile.class))
.orElse(null);
}
book.setCoverImage(coverImage);
book.setContent(bookContent);
book.setTitle(addBookResource.getTitle());
book.setDescription(addBookResource.getDescription());
book.setCategories(Arrays.stream(addBookResource.getCategories())
.map(Category::new)
.collect(Collectors.toSet()));
bookRepository.save(book);
}
}
UploadFileServiceImplementation.class
#Service
public class UploadFileServiceImplementation implements UploadFileService {
private UploadFileRepository uploadFileRepository;
private ModelMapper modelMapper;
#Autowired
public UploadFileServiceImplementation(UploadFileRepository uploadFileRepository, ModelMapper modelMapper){
this.uploadFileRepository = uploadFileRepository;
this.modelMapper = modelMapper;
}
#Transactional
#Override
public Long save(String filename, byte[] data) {
UploadFile uploadFile = new UploadFile();
uploadFile.setFileName(filename);
uploadFile.setData(data);
UploadFile saved = uploadFileRepository.save(uploadFile);
return saved.getId();
}
#Override
public Optional<FileResource> findById(Long id) {
return uploadFileRepository.findById(id)
.map(file -> modelMapper.map(file, FileResource.class));
}
}
EDIT
After a suggested changes I still got an IllegalStateException:
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'bookService': Unsatisfied dependency expressed through field 'uploadFileService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'uploadFileService': Unsatisfied dependency expressed through field 'modelMapper'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.modelmapper.ModelMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'uploadFileService': Unsatisfied dependency expressed through field 'modelMapper'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.modelmapper.ModelMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.modelmapper.ModelMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}

Step 1: Add a #Bean for Model mapper if already not there in main application class or configuration class:
#SpringBootApplication
public class Application {
public static void main(String[] args){
SpringApplication.run(Application.class, args);
}
#Bean
public ModelMapper modelMapper() {
return new ModelMapper();
}
}
Step 2: Here is how you can manage it, please make below chnages in service impl:
#Service("uploadFileService")
public class UploadFileServiceImplementation implements UploadFileService {
#Autowired
private UploadFileRepository uploadFileRepository;
#Autowired
private ModelMapper modelMapper;
//Remove constructure now.
same do for BookServiceImplementation
#Service("bookService")
public class BookServiceImplementation implements BookService {
#Autowired
private BookRepository bookRepository;
#Autowired
private UploadFileService uploadFileService;
#Autowired
private ModelMapper modelMapper;
//remove constructure

Related

Using Prototype scope to create DataSource

I'm trying to create a Prototyped Scoped Spring bean using the given configuration. The details for url, username, password, driver will be determined at runtime. Here's my configuration:
#Configuration
class Cfg {
#Bean
public Function<DataSourcePropertiesMap, DriverManagerDataSource> functionOfDriverMgrDS() {
return this::driverManagerDataSource;
}
#Lazy
#Bean
#Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public DriverManagerDataSource driverManagerDataSource(DataSourcePropertiesMap dbPropsMap) {
var ds = new DriverManagerDataSource(dbPropsMap.getDbURL(), dbPropsMap.getDbUsername(), dbPropsMap.getDbPassword());
ds.setDriverClassName(dbPropsMap.getDbDriver());
return ds;
}
}
And the DataSourcePropertiesMap is simply a container for the four arguments as below:
#Getter
#AllArgsConstructor
public class DataSourcePropertiesMap {
#NonNull private final String dbURL;
#NonNull private final String dbUsername;
#NonNull private final String dbPassword;
#NonNull private final String dbDriver;
}
Whenever, I boot the application it throws the following exception:
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'healthContributorRegistry' defined in class path resource [org/springframework/boot/actuate/autoconfigure/health/HealthEndpointConfiguration.class]: Unsatisfied dependency expressed through method 'healthContributorRegistry' parameter 2; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'dbHealthContributor' defined in class path resource [org/springframework/boot/actuate/autoconfigure/jdbc/DataSourceHealthContributorAutoConfiguration.class]: Unsatisfied dependency expressed through method 'dbHealthContributor' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'driverManagerDataSource' defined in class path resource [Cfg.class]: Unsatisfied dependency expressed through method 'driverManagerDataSource' parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'DataSourcePropertiesMap' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
Why Spring still requires arguments for DriverManagerDataSource with valid driver class for Prototyped Scoped beans. My assumption is it will register a bean someway and create a new instance whenever a call is made with the arguments. If I create a default bean of type DataSourcePropertiesMap with dummy values it requires a valid driverclass.
Editing my original answer since I have not seen this part of the question
The details for url, username, password, driver will be determined at
runtime.
As of spring boot 2.x there is still no automatic way of loading properties on runntime. You would have to manually parse the file and read those properties inside this prototype bean method.

Cannot create spring beans

I have spring application and have defined the Clock bean in my SpringMvcConfig.java as follows
#Bean
public Clock clock() {
return Clock.systemDefaultZone();
}
I am using it in my service
#Service
#RequiredArgsConstructor
#Slf4j
public class DeliveryEstimationService {
#NonNull
private final SalesChannelService salesChannelService;
#NonNull
private final MessageSource messageSource;
#NonNull
private final Clock clock;
public List<LocalDateTime> applyCutoffHoursToLocalDate(List<Integer> cutoffWindowHourList, int plusDays) {
return cutoffWindowHourList.stream().map(cutoffWindowHour -> LocalDateTime.of(
LocalDate.now(clock), LocalTime.of(cutoffWindowHour, 0)).plusDays(plusDays))
.collect(Collectors.toList());
}}
And I see this error
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:640)
... 83 more
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'deliveryEstimationService' defined in file [/home/runner/work/checkout-service/checkout-service/target/classes/com/checkout/delivery/DeliveryEstimationService.class]: Unsatisfied dependency expressed through constructor parameter 2; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.time.Clock' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:798)
Can someone tell me why spring app cannot create the bean?
I had to use clock because I need to set fixed time for testing purpose
void getFixedClock(LocalDate date) {
fixedClock = Clock.fixed(date.atStartOfDay(ZoneId.systemDefault()).toInstant(), ZoneId.systemDefault());
doReturn(fixedClock.instant()).when(clock).instant();
doReturn(fixedClock.getZone()).when(clock).getZone();
}

UnsatisfiedDependencyException during test

I use psring boot 2, postgres and Jpa with hibernate.
I would like to test one of my class
#Component
public class ExportsFacade {
private SamplesService sampleService;
private SamplesRepository sampleRepository;
#Autowired
public ExportsFacade(SamplesService sampleService, SamplesRepository sampleRepository) {
this.sampleService = sampleService;
this.sampleRepository=sampleRepository;
}
...
}
I created this test
#RunWith(SpringRunner.class)
#DataJpaTest
#AutoConfigureTestDatabase(replace=Replace.NONE)
public class ExportsFacadeTest {
#Autowired
private ExportsFacade exportsFacade;
#Test
public void export() throws IOException {
exportsFacade.generateExport();
}
}
I get this error
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'com.lcm.facade.ExportsFacadeTest':
Unsatisfied dependency expressed through field 'exportsFacade'; nested
exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type 'com.lcm.facade.ExportsFacade' available:
expected at least 1 bean which qualifies as autowire candidate.
Dependency annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true)}

DynamoDB - repository bean not found

I am trying to use spring boot together with DynamoDB. This is the hierarchy of the project:
I have the following error
WARN 79115 --- [ restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'webController': Unsatisfied dependency expressed through field 'repository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'klit.demo.repo.CustomerRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Those are my classes
#EnableScan
public interface CustomerRepository extends CrudRepository<Customer, String>{
}
#RestController
public class WebController {
#Autowired
CustomerRepository repository;
#RequestMapping("/save")
public String save() {
repository.save(new Customer("JSA-1", "Jack", "Smith"));
return "Done";
}
#RequestMapping("/findall")
public String findAll() {
String result = "";
Iterable<Customer> customers = repository.findAll();
for (Customer cust : customers) {
result += cust.toString() + "<br>";
}
return result;
}
}
it doesn't not recognize the repository as a bean ...

Autowiring not working in SpringBoot controller

Hi i was trying to work over an existing SpringBoot application. I created a service class and tried to autowire it in the existing controller, but when trying to build, its failing saying bean injection failed.
Cause: org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'controller': Injection of autowired
dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire field: private
com.disooza.www.card.dispenser.service.FilaPartnerService
com.disooza.www.card.dispenser.controller.CardDispenserController.FilaPartnerService;
nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
[com.disooza.www.card.dispenser.service.FilaPartnerService] found for
dependency: expected at least 1 bean which qualifies as autowire
candidate for this dependency. Dependency annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true)}
at
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
Following is my controller class:
#Controller
#RequestMapping(value = "/service")
public class CardController {
private static final Logger LOGGER = LoggerFactory.getLogger(CardController.class);
#Autowired
private CardDao dao;
#Autowired
private PaymentService paymentService;
#Autowired
private FilaPartnerService filaPartnerService;
FilaPartnerService is the newly created interface, and rest all autowires are working fine in this controller.
Interesting thing is when I try to place this service class in any other controller it is working fine. Any help over this issue will be appreciated, since I'm stuck with it.
This is my service interface:
#Service
public interface FilaPartnerService {
RetrievePaymentTokenResponse retrieveXXX(SupplierRequest request);
}
This is the implementation class:
#Component
public class FilaPartnerServiceImpl implements FilaPartnerService {
#Autowired
private RestTemplate restTemplate;
#Autowired
private RetrieveRequestBuilder retrieveRequestBuilder;
#Value("${filaPartner.url}")
private String filaServiceUrl;
#Override
public RetrievePaymentTokenResponse retrieveFilaPaymentToken(SupplierTokenRequest request) {
RetrievePaymentTokenResponse tokenResponse = null;
RetrievePaymentTokenRequest paymentServiceRequest = retrievePaymentTokenRequestBuilder.retrievePaymentTokenRequestBuilder(request);
try {
tokenResponse =
restTemplate.postForObject( FilaServiceUrl, paymentServiceRequest, RetrievePaymentTokenResponse.class);
} catch (RestClientException exp) {
//TO-DO return error code
}
return null;
}
}

Resources