MongoDB autowire is throwing exception - java

I have below class files and it looks everything fine but i am not understanding why i am getting autowire failure. Can anyone please help me to find the issue?
updated with package details
package com.ui.controller;
#RestController
#RequestMapping(value = "/Person")
public class PersonController {
#Autowired
#Lazy
private RepoService repoService;
}
package com.messaging.service.impl;
#Component
#Lazy
public class RepoServiceImpl implements RepoService {
#Autowired
#Qualifier("personRepository")
private PersonRepository personRepo;
}
package com.messaging.service;
public interface RepoService {
}
package com.da.repository;
#Repository("personRepository")
public interface PersonRepository extends MongoRepository<SomeType, String> {
}
package com.conf;
#Configuration
#EnableMongoRepositories(basePackages = "com.da.repository")
#EnableMongoAuditing
#Profile("mongo")
public class MongoConfig extends AbstractMongoConfiguration {
}
I am getting following error:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.da.repository.PersonRepository] 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), #org.springframework.beans.factory.annotation.Qualifier(value=personRepository)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1301)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1047)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
... 52 more

Its my bad. The issue was not with the above coding but with the mongodb connection. There was a connection issue which resulted the above error.

Related

UnsatisfiedDependencyException: Error creating bean with name in 2.4.1 Spring Boot

main Class:
package *.*.*;
#SpringBootApplication
public class UserApplication {
public static void main(String[] args) {
SpringApplication.run(UserApplication.class, args);
}
}
DBUtils.java
package *.*.*.dataaccess.dbutils;
#Service
public class DBUtils {
#Autowired
UserRepository userRepository;
public UserEntity getUserEntityById(String id) {
return userRepository.findById(id);
}
}
Repository Class:
package *.*.*.dataaccess.repository;
#Repository
public interface UserRepository extends JpaRepository<UserEntity, UserIdentity> {
UserEntity findById(String id);
}
and also UserEntity java class is in package *.*.*.dataaccess.dao;
Test Class:
#SpringBootTest
class UserApplicationTests {
#Autowired
DBUtils utils; // issue is with this
#Test
void contextLoads() {
}
}
While doing maven test for entire project and getting the below error:
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'DBUtils': Unsatisfied dependency expressed through field 'userRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type '...dataaccess.repository.UserRepository' 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 '...dataaccess.repository.UserRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
I have used #Service on DBUtils and #Repository on JpaRepository but still getting the above error and using springboot is 2.4.1.
Can anyone please help here?

Spring Boot WebFluxTest test, failed to instantiate repository, specified class is an interface

I am writing the integration tests with #WebFluxTest for my #RestController.
Here are my classes:
#RestController
#RequestMapping("/usager")
public class UsagerController {
#Autowired
private UsagerService usagerService;
#GetMapping
public Usager getUsager() {
return usagerService.create();
}
}
#Service
public class UsagerService implements CrudService<Usager, Integer> {
#Autowired
private UsagerRepository usagerRepository;
#Override
public JpaRepository<Usager, Integer> getRepository() {
return usagerRepository;
}
#Override
public Usager create() {
return new Usager();
}
}
#Repository
public interface UsagerRepository extends JpaRepository<Usager, Integer>, JpaSpecificationExecutor<Usager> {
}
#ExtendWith(SpringExtension.class)
#WebFluxTest(UsagerController.class)
#Import({ UsagerService.class, UsagerRepository.class })
#Tag(TestCase.INTEGRATION)
public class UsagerControllerIT {
#Autowired
private WebTestClient wtc;
#Test
public void getUsager_returnUsager() {
ResponseSpec rs = wtc.get().uri("/usager").exchange();
rs.expectStatus().isOk();
rs.expectHeader().contentType(MediaType.APPLICATION_JSON);
rs.expectBody(Usager.class).isEqualTo(new Usager());
}
}
I get the following exception:
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.dsi.bibliosys.biblioback.repository.UsagerRepository]: Specified class is an interface
I don't understand why Spring can't inject the repository.
Does somebody have an idea ?
I tried another approach using #SpringBootTest. Here is my new test class :
#ExtendWith(SpringExtension.class)
#SpringBootTest
#Tag(TestCase.INTEGRATION)
public class UsagerController02IT {
#Autowired
private UsagerController usagerController;
#Test
public void getUsager_returnUsager() {
WebTestClient wtc = WebTestClient.bindToController(usagerController).build();
ResponseSpec rs = wtc.get().uri("/usager").exchange();
rs.expectStatus().isOk();
rs.expectHeader().contentType(MediaType.APPLICATION_JSON);
rs.expectBody(Usager.class).isEqualTo(new Usager());
}
}
I get this exception:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.dsi.bibliosys.biblioback.controller.UsagerController': Unsatisfied dependency expressed through field 'usagerService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.dsi.bibliosys.biblioback.service.entity.UsagerService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
I don't understand why UserService is not available in the application context.
Thanks for your help.
This looks very similar to this. I'd suggest investigating your test configuration and adding it if appropriate.
A quote from Spring on #WebFluxTest
Using this annotation will disable full auto-configuration and instead apply only configuration relevant to WebFlux tests (i.e. #Controller, #ControllerAdvice, #JsonComponent, Converter/GenericConverter, and WebFluxConfigurer beans but not #Component, #Service or #Repository beans).

No qualifying bean of type 'ru.spb.repository.UserRepository' available: expected at least 1 bean which qualifies as autowire candidate

Repository class:
package ru.spb.repository.user;
#Repository
public class AnketUserRepository implements UserRepository {
#Autowired
private CrudUserRepository crudRepository;
}
Interface:
package ru.spb.repository;
public interface UserRepository {
}
Service:
package ru.spb.service;
#Service
public class UserService {
private final UserRepository repository;
#Autowired
public UserService (UserRepository repository){
this.repository = repository;
}
}
Configs:
in spring-app.xml:
<context:component-scan base-package="ru.spb.service"/>
in spring-db.xml:
<context:component-scan base-package="ru.spb.repository.user"/>
But I catch the following exception:
NoSuchBeanDefinitionException: No qualifying bean of type 'ru.spb.repository.UserRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
I tried to add #Repository on UserRepository-interface, but without success.
You need to Annotate the Interface also
package ru.spb.repository;
#Repository
public interface UserRepository {
}
Your component scan is configured only to the package of the implementing class, but you are autowiring the interface which is on a different (non component scanned) package.
Move the #Repository annotation to the inteface, and add ru.spb.repository to your component-scan
I moved
<context:component-scan base-package="ru.spb.repository.user"/>
from spring-db.xml to spring-app.xml. And this problem is solved.
However I dont understand the reason of this problem.

NoSuchBeanDefinitionException for deep inheritance

I have a Spring boot application. My repository is written in the following way:
An interface:
#NoRepositoryBean
public interface MyQueryRepository {
int checkThis(String this);
int checkThisAndThat(String this, String that);
}
An abstract Class:
public abstract class AbstractMyQueryRepository implements MyQueryRepository {
#Override
public int checkThis(String this) {...}
#Override
public int checkThisAndThat(String this, String that) {...}
}
then the implementation:
#Transactional(TVServiceDbConfigAtlanta.TV_TRANSACTION_MANAGER_NAME_ATLANTA)
#Repository
public class MyQueryRepositoryAtlanta extends AbstractMyQueryRepository {
#Autowired
public MyQueryRepositoryAtlanta (
#Qualifier(TVServiceDbConfigAtlanta.TV_DATA_SOURCE_BEAN_NAME_ATLANTA) final DataSource dataSource) {
super(dataSource);
}
}
When I try to autowire MyQueryRepositoryAtlanta in my UT in the following way:
#ExtendWith(SpringExtension.class)
#DataJpaTest
#ActiveProfiles("test")
class MyQueryRepositoryAtlantaTest{
#Autowired
private MyQueryRepositoryAtlanta myQueryRepositoryAtlanta ;
#Test
void checkThisTest() {
assertThat(myQueryRepositoryAtlanta.checkThis("ABC")).isEqualTo(1);
}
#TestConfiguration
#Profile("test")
#Import(TVServiceDbConfigAtlanta.class)
public static class Config {
}
}
I get the following error:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name
'com.myapp.MyQueryRepositoryAtlantaTest': Unsatisfied dependency
expressed through field 'myQueryRepositoryAtlanta '; nested exception
is org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type 'com.myapp.AbstractMyQueryRepository '
available: expected at least 1 bean which qualifies as autowire
candidate. Dependency annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true)}
at
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:586)
~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE] at
org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:91)
~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE] at
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:372)
~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE] at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1341)
~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE] at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:393)
~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE] at
org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:118)
~[spring-test-5.0.8.RELEASE.jar:5.0.8.RELEASE] [...]
I am not sure I understand why, since:
The bean that I am testing is annotated as #Repository and
There is no other bean called in the same way
I also checked similar answers in SOF but they are not applicable because of the particular structure that I use. Any idea about how to solve the issue?

Spring boot app works when I run it, but falls when I test it

I have a simple spring app with one controller
#RestController
public class UserController {
// #Autowired
// UserServiceImpl userService;
#RequestMapping(value="/getUser", method = RequestMethod.GET)
public String getUser(){
// return userService.greetUser();
return "Hello user";
}
It works when I start it. If I uncomment #Autowired and run with the first return statement using UserService it also works.
My Service interface
#Service
public interface UserService {
String greetUser();
void insertUsers(List<User> users);
}
and implementation
#Service
public class UserServiceImpl implements UserService{
#Override
public String greetUser() {
return "Hello user";
}
}
But when I test it, the app falls with the following errors
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userController': Unsatisfied dependency expressed through field 'userService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.demo.service.UserServiceImpl' 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 'com.example.demo.service.UserServiceImpl' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
The test class
#RunWith(SpringRunner.class)
#WebMvcTest
public class DemoApplicationTests {
#Autowired
private MockMvc mockMvc;
#Test
public void shouldReturnHelloString() throws Exception{
this.mockMvc
.perform(get("/getUser"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().string("Hello user"));
}
}
Also, if I remove
// #Autowired
// UserServiceImpl userService;
and run test with second return statement, the test execute without error. I understand that the problem is in the UserServiceImpl, but I don't know what it is. What do I need to correct?
You should try to autowire your bean by an interface, not implementation
#Autowired
UserService userService;
And also you should remove #Service from UserService interface

Categories

Resources