![](/img/trans.png)
[英]spring - boot (error while creating beans ) - org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name
[英]JAVA SPRING - org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'employeeController':
我是 Spring 的新手,正在嘗試使用 Hibernate 制作 Spring MVC 應用程序。 我在嘗試啟動應用程序時遇到問題
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'employeeController': Unsatisfied dependency expressed through field 'employeeService'; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.mchange.v2.c3p0.ComboPooledDataSource] for bean with name 'myDataSource' defined in ServletContext resource [/WEB-INF/spring-mvc-forms-servlet.xml]; nested exception is java.lang.ClassNotFoundException: com.mchange.v2.c3p0.ComboPooledDataSource
這是我的代碼
Employee.java(實體)
package com.john.springmvc.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="employee")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="id")
private int id;
@Column(name="employee_id")
private int employeeId;
@Column(name="first_name")
private String firstName;
@Column(name="last_name")
private String lastName;
@Column(name="contact_number")
private String contactNumber;
@Column(name="email_address")
private String emailAddress;
public Employee() {
}
public Employee(int employeeId, String firstName, String lastName, String contactNumber, String emailAddress) {
this.employeeId = employeeId;
this.firstName = firstName;
this.lastName = lastName;
this.contactNumber = contactNumber;
this.emailAddress = emailAddress;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getEmployeeId() {
return employeeId;
}
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getContactNumber() {
return contactNumber;
}
public void setContactNumber(String contactNumber) {
this.contactNumber = contactNumber;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
@Override
public String toString() {
return "Employee [id=" + id + ", employeeId=" + employeeId + ", firstName=" + firstName + ", lastName="
+ lastName + ", contactNumber=" + contactNumber + ", emailAddress=" + emailAddress + "]";
}
}
雇員控制器.java
package com.john.springmvc.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.john.springmvc.entity.Employee;
import com.john.springmvc.service.EmployeeService;
@Controller
public class EmployeeController {
@Autowired
private EmployeeService employeeService;
@GetMapping("/employees")
public String listEmployees(Model model) {
model.addAttribute("employee", new Employee());
model.addAttribute("listEmployees",this.employeeService.listEmployees());
return "employeeForm";
}
@PostMapping("/employee/add")
public String addPerson(@ModelAttribute("employee") Employee emp) {
if(emp.getId() == 0) {
this.employeeService.addEmployee(emp);
} else {
this.employeeService.updateEmployee(emp);
}
return "redirect:/employeeForm";
}
@RequestMapping("/remove/{id}")
public String removePerson(@PathVariable("id") int id){
this.employeeService.removeEmployee(id);
return "redirect:/employeeForm";
}
@RequestMapping("/edit/{id}")
public String editPerson(@PathVariable("id") int id, Model model){
model.addAttribute("employee", this.employeeService.getEmployeeById(id));
model.addAttribute("listEmployees", this.employeeService.listEmployees());
return "employeeForm";
}
}
EmployeeDAOImpl.java
package com.john.springmvc.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.john.springmvc.entity.Employee;
@Repository
public class EmployeeDAOImpl implements EmployeeDAO {
@Autowired
private SessionFactory sessionFactory;
@Override
public void addEmployee(Employee emp) {
Session session = this.sessionFactory.getCurrentSession();
session.save(emp);
System.out.println("Employee saved successfully: " + emp);
}
@Override
public void updateEmployee(Employee emp) {
Session session = this.sessionFactory.getCurrentSession();
session.update(emp);
System.out.println("Employee updated successfully: " + emp);
}
@Override
public List<Employee> listEmployees() {
Session session = this.sessionFactory.getCurrentSession();
List<Employee> employeeList = session.createQuery("from Employee").getResultList();
for(Employee emp : employeeList) {
System.out.println("Employee List: \n" + emp);
}
return employeeList;
}
@Override
public Employee getEmployeeById(int id) {
Session session = this.sessionFactory.getCurrentSession();
Employee emp = session.get(Employee.class, new Integer(id));
System.out.println("Getting employee with id: " + id);
return emp;
}
@Override
public void removeEmployee(int id) {
Session session = this.sessionFactory.getCurrentSession();
Employee emp = (Employee) session.get(Employee.class, new Integer(id));
if(null != emp) {
session.delete(emp);
}
System.out.println("Employee deleted successfully: " + emp);
}
}
EmployeeServiceImpl.java
package com.john.springmvc.service;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.john.springmvc.dao.EmployeeDAO;
import com.john.springmvc.entity.Employee;
@Service
public class EmployeeServiceImpl implements EmployeeService{
@Autowired
private EmployeeDAO employeeDAO;
@Override
@Transactional
public void addEmployee(Employee emp) {
this.employeeDAO.addEmployee(emp);
}
@Override
@Transactional
public void updateEmployee(Employee emp) {
this.employeeDAO.updateEmployee(emp);
}
@Override
@Transactional
public List<Employee> listEmployees() {
return this.employeeDAO.listEmployees();
}
@Override
@Transactional
public Employee getEmployeeById(int id) {
return this.employeeDAO.getEmployeeById(id);
}
@Override
@Transactional
public void removeEmployee(int id) {
this.employeeDAO.removeEmployee(id);
}
}
查看:employeeForm.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<head>
<title>Document</title>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/resources/css/style.css" />
</head>
<body>
<form action="/spring-mvc-forms/addEmployee" method="POST" modelAttribute="employee" class="form">
<h1 class="form-heading">Employee Form</h1>
<label for="employeeID" class="form-label">Employee ID: </label><br>
<input type="text" path="employeeID" id="employeeId" placeholder="Enter employee id.."/><br><br>
<label for="firstName" class="form-label">First Name: </label><br>
<input type="text" path="firstName" id="firstName" placeholder="Enter first name.."/><br><br>
<label for="lastName" class="form-label">Last Name: </label><br>
<input type="text" path="lastName" id="lastName" placeholder="Enter last name.."/><br><br>
<label for="contactNumber" class="form-label">Contact Number: </label><br>
<input type="text" path="contactNumber" id="contactNumber" placeholder="Enter contact number.."/><br><br>
<label for="emailAddress" class="form-label">Email Address: </label><br>
<input type="text" path="emailAddress" id="emailAddress" placeholder="Enter email address.."/><br><br>
<input type="submit" value="Submit" id="submitButton"/>
</form>
<h3>Employee List</h3>
<table id="t01">
<tr>
<th>Employee ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Contact Number</th>
<th>Email Address</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<c:forEach items="${listEmployees}" var="employee">
<tr>
<td>${employee.employeeId}</td>
<td>${employee.firstName}</td>
<td>${employee.lastName}</td>
<td>${employee.contactNumber}</td>
<td>${employee.emailAddress}</td>
<td><a href="<c:url value='/edit/${employee.id}' />" >Edit</a></td>
<td><a href="<c:url value='/remove/${employee.id}' />" >Delete</a></td>
</tr>
</c:forEach>
</table>
</body>
</html>
視圖:employeeView.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Employee Details</title>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/resources/css/style.css" />
</head>
<body>
<h3>Submitted Employee Information</h3>
<table>
<tr>
<td>Employee ID:</td>
<td>${employeeId}</td>
</tr>
<tr>
<td>First Name :</td>
<td>${firstName}</td>
</tr>
<tr>
<td>Last Name :</td>
<td>${lastName}</td>
</tr>
<tr>
<td>Contact Number :</td>
<td>${contactNumber}</td>
</tr>
<tr>
<td>Email Address :</td>
<td>${emailAddress}</td>
</tr>
</table>
</body>
</html>
spring-mvc-forms-servlet.xml
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
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.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- Add support for component scanning -->
<context:component-scan base-package="com.john.springmvc" />
<!-- Add support for conversion, formatting and validation support -->
<mvc:annotation-driven/>
<!-- Define Spring MVC view resolver -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- Step 1: Define Database DataSource / connection pool -->
<bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="com.mysql.cj.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring-mvc-forms?useSSL=false&serverTimezone=UTC" />
<property name="user" value="root" />
<property name="password" value="password" />
<!-- these are connection pool properties for C3P0 -->
<property name="minPoolSize" value="5" />
<property name="maxPoolSize" value="20" />
<property name="maxIdleTime" value="30000" />
</bean>
<!-- Step 2: Setup Hibernate session factory - DEPENDS ON THE DATA SOURCE -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="packagesToScan" value="com.john.springmvc.entity" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- Step 3: Setup Hibernate transaction manager -->
<bean id="myTransactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- Step 4: Enable configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="myTransactionManager" />
<!-- Step 5: Support for adding web resources: CSS, IMAGES, JS etc -->
<mvc:resources location="/resources/" mapping="/resources/**"></mvc:resources>
</beans>
網頁.xml
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>spring-mvc-forms</display-name>
<absolute-ordering />
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-mvc-forms-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
您好,此錯誤意味着您的類路徑中沒有 com.mchange.v2.c3p0.ComboPooledDataSource 類。
如果您使用 maven,您應該添加它以將 C3P0 添加到您的項目中。
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.5</version>
</dependency>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.