use spring-data-r2dbc, Unable to inject DAO interface,Field myDao in ServiceImpl required a bean of type 'UmsAddressDao' that could not be found - spring

1.illustrate
springboot 2.3.7
springboot-data-r2dbc 1.1.6
2.I used Spring-Data-R2DBC to operate mysql, but I have been reporting an errororg.springframework.beans.factory.UnsatisfiedDependencyException
3.Complete error description
cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'webFluxController': Unsatisfied dependency expressed through field 'umsAddressService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'umsAddressServiceImpl': Unsatisfied dependency expressed through field 'umsAddressDao'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.xxx.inner.UmsAddressDao' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Field umsAddressDao in com.xxx.impl.UmsAddressServiceImpl required a bean of type 'com.xxx.inner.UmsAddressDao' that could not be found.
3.My code snippet
my controller
#RestController
public class WebFluxController {
private Logger log = LoggerFactory.getLogger(WebFluxController.class);
#Autowired
private UmsAddressService umsAddressService;
#Autowired
private StringRedisTemplate stringRedisTemplate;
#Autowired
private QuestionService questionService;
// do something
}
my service
public interface UmsAddressService {
Mono<UmsAddress> findById(Long id);
}
my service impl
#Service
public class UmsAddressServiceImpl implements UmsAddressService {
#Autowired
private UmsAddressDao umsAddressDao;
#Override
public Mono<UmsAddress> findById(Long id) {
return umsAddressDao.findById(id);
}
}
my dao
#Component
public interface UmsAddressDao extends ReactiveCrudRepository<UmsAddress,Long> {
}
my model
#Data
#Accessors(chain = true)
#ToString
#Table("ums_address")
public class UmsAddress {
#Id
#Column("id")
private Long id;
#Column("member_id")
private Long memberId;
// other field
}
springbootApplication
#EnableWebFlux
#SpringBootApplication( exclude = { RedisRepositoriesAutoConfiguration.class })
#OpenAPIDefinition(info = #Info(title = "APIs", version = "1.0", description = "Documentation APIs v1.0"))
public class MyWebApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(RollkingWebApplication.class).web(WebApplicationType.REACTIVE).run(args);
}
}

Related

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

I have a test class in Junit4 that needs to use NutrientListService.
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = ApplicationContext.class)
public class CalculationTests {
private NutrientListService nutrientService;
#Test
public void someTest()
Result re = Calculator.calculate(response, nutrientService)
}
I was getting a null nutrientService, so I tried to set up an ApplicationContext.
#Configuration
#ComponentScan("myservice")
#ComponentScan("myrepository")
public class ApplicationContext {
#Autowired
NutrientListService nutrientService;
}
However, I get
Error creating bean with name 'nutrientListService': Unsatisfied dependency expressed through field 'nutrientListRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'repositories.NutrientListRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
This is the service:
#Service
#Component
public class NutrientListService {
#Autowired
private NutrientListRepository repo;
}
And the repository:
#Repository
public interface NutrientListRepository extends MongoRepository<MyClass, String> {
MyClass findByID(String ID);
}
Any ideas to wire the service properly? I need to pass it for calculation as it is one of the parameters. Do I have to use an application context class or the application-context.xml (which I could not find)? What would be the least obscure way to do this? I thank you.
#Configuration
#ComponentScan("myservice")
#ComponentScan("myrepository")
public class ApplicationContext {
#Bean
NutrientListService nutrientService(){
new NutrientListService()
}
}
And then call the Bean with #Autowired
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = ApplicationContext.class)
public class CalculationTests {
#Autowired
NutrientListService nutrientService
#Test
public void someTest()
Result re = Calculator.calculate(response, nutrientService)
}

Unsatisfied dependency during test

I have a spring boot 2.0.0 M2 application who run well.
I use autowired on constructor
#RequestMapping(value = "/rest")
#RestController
public class AddressRestController extends BaseController{
private final AddressService AddressService;
#Autowired
public AddressRestController(final AddressService AddressService) {
this.AddressService = AddressService;
}
...
}
#Service
public class AddressServiceImpl extends BaseService implements AddressService {
#Autowired
public AddressServiceImpl(final AddressRepository AddressRepository) {
this.AddressRepository = AddressRepository;
}
private final AddressRepository AddressRepository;
...
}
public interface AddressRepository extends JpaRepository<Address, Integer>, AddressRepositoryCustom {
}
#Repository
public class AddressRepositoryImpl extends SimpleJpaRepository implements AddressRepositoryCustom {
#PersistenceContext
private EntityManager em;
#Autowired
public AddressRepositoryImpl(EntityManager em) {
super(Address.class, em);
}
...
}
When i try to run a basic test
#RunWith(SpringJUnit4ClassRunner.class)
public class AddressServiceTest {
#Autowired
private AddressService service;
#MockBean
private AddressRepository restTemplate;
#Test
public void getAddress(){
MockitoAnnotations.initMocks(this);
Pageable page = PageRequest.of(0, 20);
Page<Address> pageAdr = mock(Page.class);
given(this.restTemplate.findAll(page)).willReturn(pageAdr);
Page<AddressDto> pageDto = service.getAddress(page);
}
}
I get this error
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name
'com.sonos.arcor.service.AddressServiceTest': Unsatisfied dependency
expressed through field 'service'; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type ''com.sonos.arcor.service.AddressService'
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 i get this error.
You need to annotate the test with SpringBootTest so that spring initialize an application context
https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html#boot-features-testing-spring-boot-applications
#SpringBootTest
#RunWith(SpringJUnit4ClassRunner.class)
public class AddressServiceTest {
// the remaining test
}
Also you do not need MockitoAnnotations.initMocks(this);
Spring takes care of the mock handling
When [#MockBean is]used on a field, the instance of the created mock will also be
injected. Mock beans are automatically reset after each test method
see Mocking and spying beans

MongoDB and Spring JPA integration is throwing error

I am trying to integrate Spring JPA with MongoDB. My intention is to just retrieve data from mongo DB. I am getting the below error while injecting my repository.
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.org.coop.society.data.mongo.repositories.MaterialMasterRepository com.org.coop.security.service.MongoService.materialMasterRepository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'materialMasterRepository': Invocation of init method failed; nested exception is java.lang.AbstractMethodError
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
My configuration snippet is given below.
TestMongoDBConfig.java
#Configuration
#EnableMongoRepositories(basePackages = {"com.abc.data.mongo.repositories"})
#ComponentScan(basePackages = "com.abc")
#PropertySource("classpath:applicationTest.properties")
public class TestMongoDBConfig extends AbstractMongoConfiguration {
#Autowired
private Environment env;
#Override
protected String getDatabaseName() {
return "retail";
}
#Override
#Bean
public MongoClient mongo() throws Exception {
MongoClient client = new MongoClient("localhost", 27017);
return client;
}
#Override
protected String getMappingBasePackage() {
return "com.abc.data.mongo.entities";
}
#Bean
public MongoTemplate mongoTemplate() throws Exception {
return new MongoTemplate(mongo(), getDatabaseName());
}
}
MaterialMaster.java in com.abc.data.mongo.entities package
#Document(collection = "materialMaster")
public class MaterialMaster {
#Id
private Long materialId;
#Field
private String name;
MaterialMasterRepository.java in com.abc.data.mongo.repositories package
public interface MaterialMasterRepository extends MongoRepository<MaterialMaster, Long> {
}
MongoService.java in com.abc.service package
#Service
public class MongoService {
#Autowired
private MaterialMasterRepository materialMasterRepository;
public void getMaterials() {
List<MaterialMaster> materials = materialMasterRepository.findAll();
System.out.println(materials);
}
}
Junit class looks like below
#RunWith(SpringJUnit4ClassRunner.class)
#ComponentScan(basePackages = "com.abc")
#ContextHierarchy({
#ContextConfiguration(classes={TestMongoDBConfig.class})
})
public class ModuleWSTest {
#Autowired
private MongoService mongoService;
#Test
public void testModule() {
mongoService.getMaterials();
}
}
I have tried all possible changes (as per my knowledge) but no luck. Any help is really appreciated.
The error message is little confusing. I was using latest spring-data-mongodb (1.8.4.RELEASE). Once I downgraded the dependency to 1.6.0.RELEASE then the above configuration started working.

How to wire or autowire think properly?

I like spring, I like those annotations, save me a lot of time. But it also give me headed. So can someone explain for me about #Autowired plz?
I followed some tutorial and here is what I got:
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'registerController':
Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.isad.dao.UserAccountDAO
com.isad.controller.RegisterController.userAccount; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.isad.dao.UserAccountDAO] 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)}
My Pojo:
private int id;
private String username;
private String email;
private String password;
My Dao:
#Repository
#Transactional
public class UserAccountDAOImpl implements UserAccountDAO{
#Autowired
private SessionFactory sessionFactory;
public UserAccount getById(int id) {
return (UserAccount) sessionFactory.getCurrentSession()
.get(UserAccount.class, id);
}
public int save(UserAccount aUser) {
return (Integer)sessionFactory.getCurrentSession().save(aUser);
}
}
My Controller:
#Autowired
private UserAccountDAO userAccount;
#Autowired
private UserAccountFormValidator validator;
#RequestMapping(value="register", method=RequestMethod.POST)
public String registerPage(#ModelAttribute("newUserAccount") UserAccount aUser,
BindingResult result) {
System.out.println("inside register post");
validator.validate(aUser, result);
if( result.hasErrors()) {
return "register";
}
userAccount.save( aUser );
return "../../index";
}
UserAccountFormValidator:
#Component("useraccountFormValidator")
public class UserAccountFormValidator implements Validator{
#Override
public boolean supports(Class<?> arg0) {
return UserAccount.class.isAssignableFrom( arg0 );
}
#Override
public void validate(Object arg0, Errors arg1) {
ValidationUtils.rejectIfEmptyOrWhitespace(arg1, "name", "required");
}
}
The package com.isad.dao of UserAccountDAOImpl is likely not being scanned for Spring beans. Check your Spring configuration.
Make sure your spring config file provide this:
<context:component-scan base-package="com.isad"/>

error with project in spring, hibernate

This the error that I'm getting:
SEVERE: StandardWrapper.Throwable
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'usuarioControlador': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.blah.base.database.DAO.UsuarioDAO com.blah.base.controlador.UsuarioControlador.usuarioDAO; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'UsuarioDAO' defined in file [C:\Users\Owner\workspaceSpring.metadata.plugins\org.eclipse.wst.server.core\tmp3\wtpwebapps\base\WEB-INF\classes\com\yavale\base\database\hibernetDAO\UsuarioHibernetDao.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [org.hibernate.SessionFactory]: : No qualifying bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Qualifier(value=sessionFactory)}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Qualifier(value=sessionFactory)}
This is my UsuarioControlador (controller):
#Controller
#RequestMapping("/")
public class UsuarioControlador {
private UsuarioDAO usuarioDAO;
#Autowired
public void setUsuarioDAO(UsuarioDAO usuarioDAO) {
this.usuarioDAO = usuarioDAO;
}
#RequestMapping(method = RequestMethod.GET)
public String list(Model model) {
List<Usuario> usuarios = usuarioDAO.listarUsuarios();
model.addAttribute("usuarios", usuarios);
return "index";
}
}
This is UsuarioDAO:
public interface UsuarioDAO {
void insertarUsuario(Usuario usuario);
void modificarUsuario(Usuario usuario);
List<Usuario> listarUsuarios();
Usuario buscarUsuario(String idUsuario);
void eliminarUsuario(Usuario usuario);
}
This is the class that implements UsuarioDAO:
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Service;
#Service(value="UsuarioDAO")
public class UsuarioHibernetDao extends HibernateDaoSupport implements UsuarioDAO{
#Autowired
public UsuarioHibernetDao(#Qualifier("mySessionFactory") SessionFactory
sessionFactory) {
this.setSessionFactory(sessionFactory);
}
public void insertarUsuario(Usuario usuario) {
this.getHibernateTemplate().save(usuario);
}
public void modificarUsuario(Usuario usuario) {
this.getHibernateTemplate().update(usuario);
}
public List<Usuario> listarUsuarios() {
return this.getHibernateTemplate().find("from Usuario");
}
public Usuario buscarUsuario(String idUsuario) {
return this.getHibernateTemplate().load(Usuario.class, idUsuario);
}
public void eliminarUsuario(Usuario usuario) {
this.getHibernateTemplate().delete(usuario);
}
}
This is my servlet-context.xml: https://dl.dropboxusercontent.com/u/31349296/servlet-context.xml
I'm new with spring so Im completely lost with this.
Edit: this is the complete stack trace: https://dl.dropboxusercontent.com/u/31349296/log.txt
Edit2:
You are using the wrong identifier in the Qualifier annotation. The bean id is "mySessionFactory" but you have given "sessionFactory". Also, make sure content component scan is scanning the right packages.
Update:
The other error is probably related to the import of the hibernate session. You should be using org.hibernate.Session instead of org.hibernate.classic.Session

Resources