UnsatisfiedDependencyException:创建名称为 "empController" 的 bean 时出错

UnsatisfiedDependencyException: Error creating bean with name "empController"

我想学习Spring,所以我写了简单的java CRUD 应用程序。但是从一开始我的 servlet 就有错误 org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'empController'" 和 org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dao'。我正在寻找一些解决方案,但没有任何效果。

web.xml

    <!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>

  <servlet>
    <servlet-name>Employer</servlet-name>
   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
   <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>Employer</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

雇主-servlet.xml

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

<context:component-scan base-package="com.javatpoint"></context:component-scan> 

<mvc:annotation-driven></mvc:annotation-driven>

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

<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>  
<property name="url" value="jdbc:mysql://localhost:3306/Employers"></property> 
<property name="username" value="root"></property>   
</bean>  

<bean id="jt" class="org.springframework.jdbc.core.JdbcTemplate">  
<property name="dataSource" ref="ds"></property>  
</bean>  

<bean id="dao" class="com.javatpoint.EmpDao">  
<property name="jdbcTemplate" ref="jt"></property>  
</bean>

</beans>

EmpController.java

package com.javatpoint;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class EmpController {

    @Autowired
    EmpDao empDao;

    @RequestMapping("/empform")
    public ModelAndView show() {
        return new ModelAndView("empform", "command", new Emp());
    }

    @RequestMapping(value="/save", method=RequestMethod.POST)
    public ModelAndView save(@ModelAttribute("emp")Emp emp) {
        empDao.save(emp);
        return new ModelAndView("redirect:/viewemp");
    }

    @RequestMapping("/viewemp")
    public ModelAndView viewemp() {
        List<Emp> list = empDao.getEmployees();
        return new ModelAndView("viewemp", "list", list);
    }

    @RequestMapping(value="/editemp/{id}")
    public ModelAndView edit(@PathVariable("id")int id) {
        Emp emp = empDao.getById(id);
        return new ModelAndView("empeditform", "command", emp);
    }

    @RequestMapping(value="editsave", method=RequestMethod.POST)
    public ModelAndView editsave(@ModelAttribute("emp")Emp emp) {
        empDao.update(emp);
        return new ModelAndView("redirect:/viewemp");
    }

    @RequestMapping("/delete")
    public ModelAndView delete(@ModelAttribute("emp")Emp emp) {
        empDao.delete(emp);
        return new ModelAndView("redirect:/viewemp");
    }
}

EmpDao.java

package com.javatpoint;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

public class EmpDao {

    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public int save(Emp emp) {
        String sql = "insert into Employers values('"+emp.getId()+"','"+emp.getName()+"','"+emp.getSalary()+"','"+emp.getDesignation()+"')";
        return jdbcTemplate.update(sql);
    }

    public int update(Emp emp) {
        String sql = "update Employers set name='"+emp.getName()+"',salary='"+emp.getSalary()+"',designation='"+emp.getDesignation()+"' where id='"+emp.getId()+"'";
        return jdbcTemplate.update(sql);
    }

    public int delete(Emp emp) {
        String sql = "delete from Employers where id='"+emp.getId()+"'";
        return jdbcTemplate.update(sql);
    }

    public Emp getById(int id) {
        String sql = "select * form Employers where id=?";
        return jdbcTemplate.queryForObject(sql, new Object[] {id}, new BeanPropertyRowMapper<Emp>(Emp.class));
    }

    public List<Emp> getEmployees(){
        return jdbcTemplate.query("select * from Employers", new RowMapper<Emp>() {
            public Emp mapRow(ResultSet rs, int row) throws SQLException{
                Emp emp = new Emp();
                emp.setId(rs.getInt(1));
                emp.setName(rs.getString(2));
                emp.setSalary(rs.getFloat(3));
                emp.setDesignation(rs.getString(4));
                return emp;
            }
        });
    }
}

Emp.java

package com.javatpoint;

public class Emp {

    private int id;
    private String name;
    private float salary;
    private String designation;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public float getSalary() {
        return salary;
    }
    public void setSalary(float salary) {
        this.salary = salary;
    }
    public String getDesignation() {
        return designation;
    }
    public void setDesignation(String designation) {
        this.designation = designation;
    }


}

主要问题是您试图在没有 EmpDao bean 的情况下将 EmpDao 自动连接到您的控制器。

为了使 EmpDao 成为一个 bean,您应该使用 @Component 、@Service 或 @Repository:

注释 EmpDao class
@Service
public class EmpDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public int save(Emp emp) {
        String sql = "insert into Employers values('"+emp.getId()+"','"+emp.getName()+"','"+emp.getSalary()+"','"+emp.getDesignation()+"')";
        return jdbcTemplate.update(sql);
    }

    public int update(Emp emp) {
        String sql = "update Employers set name='"+emp.getName()+"',salary='"+emp.getSalary()+"',designation='"+emp.getDesignation()+"' where id='"+emp.getId()+"'";
        return jdbcTemplate.update(sql);
    }

    public int delete(Emp emp) {
        String sql = "delete from Employers where id='"+emp.getId()+"'";
        return jdbcTemplate.update(sql);
    }

    public Emp getById(int id) {
        String sql = "select * form Employers where id=?";
        return jdbcTemplate.queryForObject(sql, new Object[] {id}, new BeanPropertyRowMapper<Emp>(Emp.class));
    }

    public List<Emp> getEmployees(){
        return jdbcTemplate.query("select * from Employers", new RowMapper<Emp>() {
            public Emp mapRow(ResultSet rs, int row) throws SQLException{
                Emp emp = new Emp();
                emp.setId(rs.getInt(1));
                emp.setName(rs.getString(2));
                emp.setSalary(rs.getFloat(3));
                emp.setDesignation(rs.getString(4));
                return emp;
            }
        });
    }
}

记住,您只能将其他 bean 注入(或自动装配)到您的 bean 中。

在 spring 中,应用程序创建它自己的 bean(作为单例,或者在您需要的任何时候作为 'new' 实例。)

EmpController 例如用@Controller 注释来告诉 spring 确切地说-这是一个控制器,当应用程序启动时,请创建这个 bean 的新实例,以便我可以使用它。

然而,当 spring 尝试创建这个 bean 时,它也会填充它的变量。 @Autowired 在 empDao 变量上的意思大致是:"you should already have built an instance of the class empDao, so please, let me have here a reference to it(empDao) so I can call it from this class(empController)"

@Controller
public class EmpController {

    @Autowired
    EmpDao empDao;

但似乎 empDao 本身 配置不正确- 没有注释让 spring 知道它应该在启动时创建它的实例。 尝试以下 2 项更改:

@Service
public class EmpDao {

@Entity
public class Emp {