Spring autowire не удалось через несколько слоев
Пока я пытаюсь разработать webapi с помощью Spring Dao, я не могу определить зависимости. Ниже приведен мой код, пожалуйста, кто-нибудь поможет мне решить эту проблему.
Структура папок проекта: -
EmployeeDAOImpl.java: -
package com.emp.dao;
@Repository
public class EmployeeDAOImpl implements EmployeeDAO {
@Autowired
@Qualifier(value = "datasource")
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
@Override
public int save(Employee emp) throws Exception {
// TODO Auto-generated method stub
return 0;
}
@Override
public boolean update(Employee emp) throws Exception {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean delete(Employee emp) throws Exception {
// TODO Auto-generated method stub
return false;
}
@Override
public Employee findById(int id) throws Exception {
// TODO Auto-generated method stub
return null;
}
@Override
public List<Employee> findAll() throws Exception {
// TODO Auto-generated method stub
return null;
}
}
EmployeeBOImpl: -
package com.emp.business;
@Service
public class EmployeeBOImpl implements EmployeeBO{
@Autowired
EmployeeDAOImpl employeeImpl;
public void setEmployeeImpl(EmployeeDAOImpl employeeImpl) {
this.employeeImpl = employeeImpl;
}
@Override
public int save(Employee emp) throws Exception {
// TODO Auto-generated method stub
return 0;
}
@Override
public boolean update(Employee emp) throws Exception {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean delete(Employee emp) throws Exception {
// TODO Auto-generated method stub
return false;
}
@Override
public Employee findById(int id) throws Exception {
// TODO Auto-generated method stub
return null;
}
@Override
public List<Employee> findAll() throws Exception {
// TODO Auto-generated method stub
return null;
}
}
EmployeeController: -
package com.emp.controller;
@Controller
public class EmployeeController{
@Autowired
private EmployeeBOImpl employeeBO;
public void setEmployeeBO(EmployeeBOImpl employeeBO) {
this.employeeBO = employeeBO;
}
}
config.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:component-scan base-package="com.emp.controller" />
<context:component-scan base-package="com.emp.business" />
<context:component-scan base-package="com.emp.aop" />
<context:component-scan base-package="com.emp.dao" />
<context:annotation-config />
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" autowire-candidate="true">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/student" />
<property name="username" value="root" />
<property name="password" value="password" />
<!-- <property name="maxTotal" value="20" />
<property name="maxIdle" value="5" /> -->
<!-- <property name="maxWaitMillis" value="5000" /> -->
</bean>
<!-- <bean id="empController" class="com.emp.controller.EmployeeController">
</bean> -->
</beans>
EmployeeTest.java: -
package com.emp.test;
public class EmployeeTest {
public static void main(String args[]){
ConfigurableApplicationContext cap = new ClassPathXmlApplicationContext("resources/config.xml");
}
}
Исключение: -
WARNING: Exception encountered during context initialization - cancelling refresh attempt:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.emp.business.EmployeeBOImpl com.emp.controller.EmployeeController.employeeBO; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeBOImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.emp.dao.EmployeeDAOImpl com.emp.business.EmployeeBOImpl.employeeImpl; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeDAOImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.sql.DataSource com.emp.dao.EmployeeDAOImpl.dataSource; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'datasource' defined in class path resource [resources/config.xml]: Error setting property values; nested exception is org.springframework.beans.PropertyBatchUpdateException; nested PropertyAccessExceptions (1) are:
PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'driverClassName' threw exception; nested exception is java.lang.IllegalStateException: Could not load JDBC driver class [com.mysql.jdbc.Driver]
2 ответа
Решение
Похоже, вы скучаете по mysql-connector.jar
в вашем классе:
Could not load JDBC driver class [com.mysql.jdbc.Driver]
Вам нужно включить драйвер mysql jdbc в путь к классам. Вы можете получить банку с https://dev.mysql.com/downloads/connector/j/ или использовать зависимость Maven
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
или эквивалент для вашей системы сборки.
Также избегайте классов реализации автопроводки для ваших зависимостей. Это тесно связывает ваше приложение. Вместо
@Autowired
EmployeeDAOImpl employeeImpl;
использование
@Autowired
EmployeeDAO employeeDao;