DynamoDB - repository bean not found - spring-boot

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 ...

Related

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)}

Spring Boot - Can't handle IllegalStateException

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

"I need required a bean of type" Error : Spring-boot

I get an error when I try to execute SpringBoot. because I need a " bean ", I don't understand why I get this, I have all annotations
17-09-2018 12:24:53.905 [restartedMain] WARN o.s.b.c.e.AnnotationConfigEmbeddedWebApplicationContext.refresh - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'parameterController': Unsatisfied dependency expressed through field 'pgService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'parameterServiceImp': Unsatisfied dependency expressed through field 'pgRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'es.my.repository.ParameterRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
With more error :
APPLICATION FAILED TO START
Description:
Field pgRepository in es.service.ParameterServiceImp required a bean of type 'es.repository.ParameterRepository' that could not be found.
Action:
Consider defining a bean of type 'es.repository.ParameterRepository' in your configuration.
I have in my controller -> with #Autowired
#RestController
#RequestMapping(value = { "/param" })
#CrossOrigin
public class ParameterController {
#Autowired
ParameterService pgService;
#RequestMapping(method = RequestMethod.GET, value = "/get", produces =
MediaType.APPLICATION_JSON_VALUE)
public List<Parameter> getAllParameters() {
List<Parameter> list = pgService.selectAll();
return list;
}
In my service -> I don't use annotations
public interface ParameterService {
public List<Parameter> selectAll();
}
Imple-> I use Service and Autowired
#Service
public class ParameterServiceImp implements ParameterService {
#Autowired
ParameterRepository pgRepository;
public List<Parameter> selectAll() {
return pgRepository.findAll());
}
}
Repository -> Here , I have querys.
public interface ParameterRepository extends CrudRepository<Parameter, String> {
}
Model ->
My POJO
#Entity
#Table(name = "Parameter")
public class Parameter {
#Id
#NotNull
#Column(name = "ID")
private String id;
#NotNull
#Column(name = "name")
private String name;
// getters setters and construct
}
I have #Entity , #Service , #Autowired but I get an error
If you use #SpringBootApplication with no basePackage specified, it will default to the current package. Just like you add #ComponentScan and #EnableJpaRepositories with no base package.
If you have set a different package to #SpringBootApplication make sure you also add #EnableJpaRepositories with proper basePackage. Repositories won't be recognized only by #ComponentScan(or declaring them as beans by any other ways explicitly or implicitly).
Try adding the next annotation.
#EnableJpaRepositories(basePackages = {"<repository-package-here>"})
is a.some.package package for your #SpingbootApplication?
other wise you need to add component scan annotation for your base package that is a.some.package

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