MD. Nashid Kamal
MD. Nashid Kamal

Reputation: 5

Injection of autowired dependencies failed; Could not autowire field; nested exception in services>DAO>HibernateTemplate>SessionFactory creating

Please Help me to solve this issue

Error Log:

    WARNING: Exception encountered during context initialization-cancelling refresh attempt org.springframework.beans.factory.BeanCreationException:
    Error creating bean with name'accountController': Injection of autowired dependencies failed; 
nested exception is org.springframework.beans.factory.BeanCreationException:
    Could not autowire field: private org.sharktooth.gms.service.UserService org.sharktooth.gms.controller.AccountController.userService;
    nested exception is org.springframework.beans.factory.BeanCreationException:
    Error creating bean with name'userService':
    Injection of autowired dependencies failed;
    nested exception is org.springframework.beans.factory.BeanCreationException:
    Could not autowire field: private org.sharktooth.gms.dao.UserDAO org.sharktooth.gms.service.implementation.UserServiceImplementation.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.springframework.orm.hibernate4.HibernateTemplate org.sharktooth.gms.dao.implementation.UserDAOImplementation.hibernateTemplate;
    nested exception is org.springframework.beans.factory.BeanCreationException:
    Error creating bean with name'hibernateTemplate'
    defined in ServletContext resource[/WEB-INF/Spring-Dispatcher-servlet.xml]:
    Cannot resolve
    reference to bean'sessionFactory'while
    setting bean property'sessionFactory';
    nested exception
    is org.springframework.beans.factory.BeanCreationException:
    Error creating
    bean with name'sessionFactory'
    defined in ServletContext resource[/WEB-INF/Spring-Dispatcher-servlet.xml]:
    Invocation of
    init method failed;
    nested exception
    is java.lang.NoClassDefFoundError:net/bytebuddy/NamingStrategy

Controller Class:

package org.sharktooth.gms.controller;

import javax.validation.Valid;

import org.sharktooth.gms.model.User;
import org.sharktooth.gms.model.UserLogin;
import org.sharktooth.gms.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping(value = "/account")
public class AccountController {

    @Autowired
    private UserService userService;

    public UserService getUserService() {
        return userService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public ModelAndView loginPage(Model dataModel) {
        ModelAndView model = new ModelAndView("login");
        dataModel.addAttribute("userLogin", new UserLogin());
        return model;
    }

    @RequestMapping(value = "/login-success", method = RequestMethod.POST)
    public ModelAndView loginSuccessPage(@Valid@ModelAttribute("userLogin")UserLogin userLogin, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return new ModelAndView("login");
        }

        ModelAndView model = new ModelAndView("users/dashboard");
        User user = getUserService().validateUserCredential(userLogin.getEmail(), userLogin.getPassword());
        if (user != null) {
            model.addObject("user", user);
            return model;
        }else {
            model.setViewName("login");
            model.addObject("loginErrorMsg", "Wrong username or password.");
            model.addObject("modelErrorMsg2", "Please try again !!");
        }
        return model;
    }

    @RequestMapping(value = "/registration", method = RequestMethod.GET)
    public ModelAndView registrationPage(Model dataModel) {
        ModelAndView model = new ModelAndView("registration");
        dataModel.addAttribute("user", new User());
        return model;
    }

    @RequestMapping(value = "/registration-success", method = RequestMethod.POST)
    public ModelAndView registrationSuccessPage(@Valid@ModelAttribute("user")User user, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return new ModelAndView("registration");
        }
        getUserService().registerUser(user);
        ModelAndView model = new ModelAndView("login");
        model.addObject("user", user);
        model.addObject("regSuccessMsg1", "Registration Successfull.");
        model.addObject("regSuccessMsg2", "Please wait for an approval from guild admin.");
        return model;
    }

    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public ModelAndView logOut() {
        ModelAndView model = new ModelAndView("home");

        return model;
    }
}

DAO Class:

package org.sharktooth.gms.dao.implementation;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.sharktooth.gms.dao.UserDAO;
import org.sharktooth.gms.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

@Component("userDAO")
public class UserDAOImplementation implements UserDAO {

    @Autowired
    private HibernateTemplate hibernateTemplate;

    public HibernateTemplate getHibernateTemplate() {
        return hibernateTemplate;
    }

    public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
        this.hibernateTemplate = hibernateTemplate;
    }

    @Override
    public boolean saveUser(User user) {
        int id = (Integer) hibernateTemplate.save(user);
        if (id > 0) {
            return true;
        }
        return false;
    }

    @SuppressWarnings("unchecked")
    @Override
    public User getUserDetailsByEmailAndPassword(String email, String password) {
        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(User.class);
        detachedCriteria.add(Restrictions.eq("email", email));
        detachedCriteria.add(Restrictions.eq("password", password));
        List<User> findByCriteria = (List<User>) hibernateTemplate.findByCriteria(detachedCriteria);
        if (findByCriteria != null && findByCriteria.size() > 0) {
            return findByCriteria.get(0);
        }else {
            return null;
        }
    }

}

Services Class:

package org.sharktooth.gms.service.implementation;

import org.sharktooth.gms.dao.UserDAO;
import org.sharktooth.gms.model.User;
import org.sharktooth.gms.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("userService")
public class UserServiceImplementation implements UserService {

    @Autowired
    private UserDAO userDAO;

    public UserDAO getUserDAO() {
        return userDAO;
    }

    public void setUserDAO(UserDAO userDAO) {
        this.userDAO = userDAO;
    }

    @Override
    public User validateUserCredential(String email, String password) {
        User user = getUserDAO().getUserDetailsByEmailAndPassword(email, password);
        return user;
    }

    @Override
    public boolean registerUser(User user) {
        boolean isRegister = false;
        boolean saveStudent = getUserDAO().saveUser(user);
        if (saveStudent) {
            isRegister = true;
        }

        return isRegister;
    }

}

Bean Configuration:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.2.xsd">
    <mvc:annotation-driven />

    <context:component-scan base-package="org.sharktooth.gms.controller"></context:component-scan>
    <context:component-scan base-package="org.sharktooth.gms.dao.implementation"></context:component-scan>
    <context:component-scan base-package="org.sharktooth.gms.service.implementation"></context:component-scan>

    <bean name="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${driver.class.name}"></property>
        <property name="url" value="${db.url}"></property>
        <property name="username" value="${db.username}"></property>
        <property name="password" value="${db.password}"></property>
    </bean>

    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate">
        <property name="sessionFactory" ref="sessionFactory"></property>
        <property name="checkWriteOperations" value="false"></property>
    </bean>

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="annotatedClasses">
            <array>
                <value>org.sharktooth.gms.model.User</value>
            </array>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
            </props>
        </property>
    </bean>

    <bean
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <array>
                <value>
                    /WEB-INF/database.properties
                </value>
            </array>
        </property>
    </bean>

    <bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="/WEB-INF/errorMessage"></property>
    </bean>

</beans>

It seems something wrong with autowiring with spring while it's trying to create private UserService userService; bean. For reference i've gone through these.

Injection of autowired dependencies failed;

context:component-scan" is not bound

Injection of autowired dependencies failed while trying to access dao bean

These doesn't solved my problem, because i've already those in my codes. But from error log, theremaybe also problem related to creating hibernate template because it's in nested error list. I'm still trying it for a lot of time, but not getting any output. Can anyone explain why it's showing failed injection? Because i've already follow the rules, And some reference are above that doesn't solve my problem. Thanks.

Upvotes: 0

Views: 2590

Answers (1)

Moler
Moler

Reputation: 995

Why you have something like this ?

@Service("userService")

just use @Service instead.

And same for the @Component("userDAO") change it for @Compoment or even better @Repository because it's dao class

Upvotes: 1

Related Questions