Injection of autowired dependencies failed (spring and hibernate) - spring

i found many topics about my error but not the same situation so i don't thing that this subject is duplicated.
here is the controller:
#ManagedBean
#Named
public class UserController {
#Inject
public UserManager userManager;
...
}
Dao:
#Named
#Transactional("transactionManager")
public class UserDAO {
#Inject
private SessionFactory sessionFactory;
//...
}
User manager :
#Named
public class UserManager {
#Inject
public UserDAO userDAO;
//...
}
UserModel (ModelView):
public class UserModel {
private String login;
private String pwd;
private String pwdConfirm;
//...
}
One to Many relation :
#Entity
#Table(name = "role", catalog = "dbusiness")
public class Role implements java.io.Serializable {
private int roleId;
private String code;
private String label;
private User user;
}
#Entity
#Table(name = "user", catalog = "dbusiness")
public class User implements java.io.Serializable {
private int userId;
private String login;
private String pwd;
private Integer enabled;
private Set<Role> roles = new HashSet<Role>(0);
}
User can have many roles, and one role can be affected in the sime time to many users, that's why i used One to many relation, i didn't put all lignes of code because of stackOverflow rules :p
So when i start tomcat server i get this error message :
Error creating bean with name 'userController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public com.keylesson.manager.UserManager com.keylesson.controller.UserController.userManager; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userManager': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public com.keylesson.dao.UserDAO com.keylesson.manager.UserManager.userDAO; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDAO': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.keylesson.dao.UserDAO.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/spring-hibernate.xml]: Invocation of init method failed; nested exception is org.hibernate.MappingException: An AnnotationConfiguration instance is required to use <mapping class="com.keylesson.persistence.User"/>

Related

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

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

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"/>

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'personController': Injection of autowired dependencies

Can any one solve this
i am getting the below error which runs on eclipse
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'personController': Injection of autowired dependencies failed; nested
exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.spring.service.CustomerService
com.spring.controller.PersonController.customerService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name
'customerService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.spring.repository.CustomerRepository com.spring.service.CustomerServiceImpl.customerRepository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.spring.repository.CustomerRepository] 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)}
i have the following
1.PersonController (class)
2.Person (class)
3.CustomerService (interface)
4.CustomerServiceImpl (class)
5.CustomerRepository (interface)
package com.spring.controller
in PersonController (class)
=====================
#Autowired
private CustomerService customerService;
#RequestMapping(value = "/person", method = RequestMethod.GET)
public String getPersonList(ModelMap model) {
model.addAttribute("personList", customerService.findAlls());
return "output";
}
package com.spring.service
in CustomerService (interface)
==================
public List<Person> findAlls();
package com.spring.service
in CustomerServiceImpl
=====================
#Service("customerService")
public class CustomerServiceImpl implements CustomerService {
#Autowired
private CustomerRepository customerRepository;
public List<Person> findAlls() {
List<Person> usersList = customerRepository.findAll();
return null;
}
}
package com.spring.repository
in CustomerRepository
===========================
#Repository("customerRepository")
public interface CustomerRepository extends MongoRepository<Person, String> {
public List<Person> findAll();
}
thanks and regards

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