当前位置: 首页 > 知识库问答 >
问题:

自动连线依赖项注入失败;无法自动连线字段;服务>DAO>Hibernate模板>SessionFactory创建中的嵌套异常

孙朗
2023-03-14

请帮我解决这个问题

错误日志:

    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

控制器类:

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类:

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

}

服务等级:

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配置:

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

当spring试图创建< code > private UserService UserService时,它的自动连接似乎有问题; bean。作为参考,我检查了这些。

自动连线依赖项的注入失败;

上下文:组件扫描“未绑定

注入自动安装的依赖项失败,而试图访问道bean

这些并没有解决我的问题,因为我的代码中已经有这些了。但从错误日志来看,创建Hibernate模板可能也有问题,因为它在嵌套错误列表中。我仍然尝试了很多时间,但没有得到任何输出。有人能解释为什么注射失败吗?因为我已经遵守了规则,上面的一些参考并不能解决我的问题。谢谢

共有1个答案

越开畅
2023-03-14

你为什么有这样的东西?

@Service(“用户服务”)

只需改用@Service。

对于@Component(“userDAO”)来说也是如此,将其更改为@Compoment甚至更好的@Repository因为它是 dao 类

 类似资料: