UnsatisfiedDependencyException:创建名为'homeController'的bean时出错:通过字段'userDAO'表示不满意的依赖关系

时间:2017-01-10 10:24:11

标签: spring exception dependencies

我正在尝试连接后端和前端两个独立的eclipse spring maven项目。我已经添加了依赖性。但是当我在Homecontroller.java中写下验证凭证逻辑时,在服务器上运行后它会显示此异常。请帮忙解决它我已经尝试了很多方法,请建议。

HomeController.java

package com.yogesh.shoponlinefrontend.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.yogesh.shoponlineback.dao.UserDAO;
import com.yogesh.shoponlineback.model.User;

@Controller
public class HomeController {


@Autowired
UserDAO userDAO;


@RequestMapping("/")
public String homePage() {
    System.out.println("Executing  the method homePage");
    return "home";
}

@RequestMapping("/login")
public ModelAndView showLoginPage() {

    ModelAndView mv = new ModelAndView("home");
    mv.addObject("msg", "You clicked login link");
    mv.addObject("showLoginPage", "true");
    return mv;
}

@RequestMapping("/register")
public ModelAndView showRegistrationPage() {
    ModelAndView mv = new ModelAndView("home");

    mv.addObject("msg", "You clicked Registration link ");

    mv.addObject("showRegistrationPage", "true");

    return mv;
}

@RequestMapping("/validate")
public ModelAndView validate(@RequestParam("id") String id, @RequestParam("password") String pwd) {
    System.out.println("In validate method");
    System.out.println("id: " + id);
    System.out.println("pwd: " + pwd);
    ModelAndView mv = new ModelAndView("home");

    if (userDAO.validate(id, pwd) != null) {
        mv.addObject("successMsg", "You logged in successfully");
    } else {
        mv.addObject("errorMsg", "Invalid Credentials..Please try again");
    }

    return mv;
}

}

UserDAO.java

package com.yogesh.shoponlineback.dao;

import java.util.List;

import com.yogesh.shoponlineback.model.User;

public interface UserDAO {

public List<User> list();

public User get(String username);

public User validate(String username, String password);

public boolean save(User user);

public boolean update(User user);
}

User.java

package com.yogesh.shoponlineback.model;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;

import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.stereotype.Component;

@Entity
//cha
@Table(name="USER")  
@Component
public class User {

@Id
private String username;

@NotEmpty(message = "please enter your name")
private String name;

@Min(5)
@Max(15)
private String password;
private String mobile;
private String role;

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}


public String getMobile() {
    return mobile;
}

public void setMobile(String mobile) {
    this.mobile = mobile;
}

public String getRole() {
    return role;
}

public void setRole(String role) {
    this.role = role;
}

}

UserDAOImpl.java

package com.yogesh.shoponlineback.daoimpl;

import java.util.List;


import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yogesh.shoponlineback.dao.UserDAO;
import com.yogesh.shoponlineback.model.User;

@Service
@Repository()
public class UserDAOImpl implements UserDAO {


@Autowired
UserDAO userDAO;

@Autowired
private SessionFactory sessionFactory;
public UserDAOImpl(SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;
}

public UserDAOImpl() {
    // TODO Auto-generated constructor stub
}

@Transactional
public List<User> list() {
    String hql = "from User";
    Query query = sessionFactory.getCurrentSession().createQuery(hql);
    return query.list();
}

@Transactional
public User get(String username) {
    return (User) sessionFactory.getCurrentSession().get(User.class, username);
}

@Transactional
public  User validate(String username, String password) {
    String hql = "from User WHERE username ='" + username + "' and password='" + password + "'";
    Query query = sessionFactory.getCurrentSession().createQuery(hql);
    return (User)query.uniqueResult();
}

@Transactional
public boolean save(User user) {
    try {
        sessionFactory.getCurrentSession().save(user);
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }

    return true;
}

@Transactional
public boolean update(User user) {
    try {
        sessionFactory.getCurrentSession().update(user);
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

}

::::::::::::::::::::::::::::::::: strong>异常追踪 ::::::::: :::::::::::::::::::::::::

INFO: FrameworkServlet 'dispatcher': initialization started
Jan 10, 2017 3:19:22 PM **org.springframework.web.context.support.AnnotationConfigWebApplicationContext prepareRefresh
INFO: Refreshing WebApplicationContext for namespace 'dispatcher-servlet': startup date [Tue Jan 10 15:19:22 IST 2017]; root of context hierarchy
Jan 10, 2017 3:19:22 PM org.springframework.web.context.support.AnnotationConfigWebApplicationContext loadBeanDefinitions
INFO: Registering annotated classes: [class com.yogesh.shoponlinefrontend.config.AppConfig]
Jan 10, 2017 3:19:23 PM org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor <init>
INFO: JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
Jan 10, 2017 3:19:23 PM org.springframework.web.context.support.AnnotationConfigWebApplicationContext refresh
WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'homeController': Unsatisfied dependency expressed through field 'userDAO'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.yogesh.shoponlineback.dao.UserDAO' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
Jan 10, 2017 3:19:23 PM org.springframework.web.servlet.DispatcherServlet initServletBean
SEVERE: Context initialization failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'homeController': Unsatisfied dependency expressed through field 'userDAO'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.yogesh.shoponlineback.dao.UserDAO' 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:592)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:370)
    at `enter code here`org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1219)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:551)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:754)
    at** org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:668)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:540)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:494)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1183)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:992)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4903)

2 个答案:

答案 0 :(得分:4)

我已更新到此:

@ComponentScan(basePackages = "com.yogesh.shoponlinefrontend,com.yogesh.shoponlineback") 

来自

@ComponentScan(basePackages = "com.yogesh.shoponlinefrontend) 

它现在工作正常。

答案 1 :(得分:0)

我遇到了同样的问题!我的POM文件配置错误。 检查您的依赖关系(版本)。 此配置对我有用。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.stoliarenko</groupId>
    <artifactId>CustomerTracker</artifactId>
    <version>0.0.1-SNAPSHOT</version>
<!--    <version>1.0-SNAPSHOT</version>-->
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>

            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <packaging>war</packaging>

    <properties>
        <failOnMissingWebXml>false</failOnMissingWebXml>
        <spring.version>5.1.0.RELEASE</spring.version>
        <hibernate.version>5.3.5.Final</hibernate.version>
        <hibernate.validator>5.4.1.Final</hibernate.validator>
        <c3p0.version>0.9.5.2</c3p0.version>
        <jstl.version>1.2.1</jstl.version>
        <tld.version>1.1.2</tld.version>
        <servlets.version>3.1.0</servlets.version>
        <jsp.version>2.3.1</jsp.version>
        <hsqldb.version>1.8.0.10</hsqldb.version>
    </properties>



    <dependencies>
        <!-- Spring MVC Dependency -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- Spring ORM -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- Hibernate Core -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.2.17.Final</version>
        </dependency>
        <!-- Hibernate Validator -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>${hibernate.validator}</version>
        </dependency>
        <!-- JSTL Dependency -->
        <dependency>
            <groupId>javax.servlet.jsp.jstl</groupId>
            <artifactId>javax.servlet.jsp.jstl-api</artifactId>
            <version>${jstl.version}</version>
        </dependency>
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>${tld.version}</version>
        </dependency>

        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>${servlets.version}</version>
            <scope>provided</scope>
        </dependency>
        <!-- JSP Dependency -->
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>${jsp.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
    </dependencies>
</project>