gpt4 book ai didi

java - 创建名称为 'employeeController' : Injection of autowired dependencies failed 的 bean 时出错

转载 作者:行者123 更新时间:2023-12-02 02:22:54 25 4
gpt4 key购买 nike

我尝试使用 MvcConfiguration.java 作为 Dispatcher 文件进行配置。但是在为 Controller 和 DAO 文件创建 bean 时它会抛出错误。

我知道 stackoverflow 上有很多关于此错误的问题。但我无法解决并陷入困境。

以下是我发现以下错误的文件。

EmployeeController.java

package com.jwt.controller;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.jboss.logging.Logger;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.jwt.model.Employee;
import com.jwt.service.EmployeeService;

@Controller
public class EmployeeController {

private static final Logger logger = Logger
.getLogger(EmployeeController.class);

public EmployeeController() {
System.out.println("EmployeeController()");
}

@Autowired
private EmployeeService employeeService;

@RequestMapping(value = "/")
public ModelAndView listEmployee(ModelAndView model) throws IOException {
List<Employee> listEmployee = employeeService.getAllEmployees();
model.addObject("listEmployee", listEmployee);
model.setViewName("home");
return model;
}

@RequestMapping(value = "/newEmployee", method = RequestMethod.GET)
public ModelAndView newContact(ModelAndView model) {
Employee employee = new Employee();
model.addObject("employee", employee);
model.setViewName("EmployeeForm");
return model;
}

@RequestMapping(value = "/saveEmployee", method = RequestMethod.POST)
public ModelAndView saveEmployee(@ModelAttribute Employee employee) {
if (employee.getId() == 0) { // if employee id is 0 then creating the
// employee other updating the employee
employeeService.addEmployee(employee);
} else {
employeeService.updateEmployee(employee);
}
return new ModelAndView("redirect:/");
}

@RequestMapping(value = "/deleteEmployee", method = RequestMethod.GET)
public ModelAndView deleteEmployee(HttpServletRequest request) {
int employeeId = Integer.parseInt(request.getParameter("id"));
employeeService.deleteEmployee(employeeId);
return new ModelAndView("redirect:/");
}

@RequestMapping(value = "/editEmployee", method = RequestMethod.GET)
public ModelAndView editContact(HttpServletRequest request) {
int employeeId = Integer.parseInt(request.getParameter("id"));
Employee employee = employeeService.getEmployee(employeeId);
ModelAndView model = new ModelAndView("EmployeeForm");
model.addObject("employee", employee);

return model;
}

}

pom.xml

<?xml version="1.0"?>
<!DOCTYPE project PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0 dtd">
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.jwt.spring</groupId>

<artifactId>SpringMVCHibernateCRUD</artifactId>

<packaging>war</packaging>

<version>1.0-SNAPSHOT</version>

<name>SpringMVCHibernateCRUD Maven Webapp</name>

<url>http://maven.apache.org</url>

<!-- Specifying the Versions of Spring, Hiberante, MySQL etc -->

<properties>
<spring.version>4.1.6.RELEASE</spring.version>
<hibernate.version>4.3.8.Final</hibernate.version>
<mssql.version>4.0</mssql.version>
<junit-version>4.11</junit-version>
<servlet-api-version>3.1.0</servlet-api-version>
<jsp-version>2.2.1</jsp-version>
<jstl-version>1.2</jstl-version>
<java.version>1.7</java.version>
</properties>

<dependencies>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.1.6.RELEASE</version>
<scope>test</scope>
</dependency>

<!-- Hibernate 4 dependencies -->

<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.8.Final</version>
</dependency>

<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>4.3.8.Final</version>
</dependency>

<!--MSSQL Connector -->

<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>6.1.0.jre8</version>
<scope>test</scope>
</dependency>

<!-- Servlet and JSP -->

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>

</dependency>


<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.2.1</version>
<scope>provided</scope>
</dependency>

<!-- JSTL dependency -->


<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->



<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>

<!-- JUnit -->



<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>

</dependencies>


<build>
<finalName>SpringMVCHibernateCRUD</finalName>
<plugins>


<plugin>
<artifactId>maven-surefire-plugin</artifactId>


<configuration>


<includes>

<include>**/*Tests.java</include>

</includes>

</configuration>

</plugin>


<plugin>

<artifactId>maven-compiler-plugin</artifactId>

<version>2.3.2</version>


<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>

</plugin>

</plugins>

</build>

</project>

MvcConfiguration.java

package com.jwt;

import javax.sql.DataSource;

import com.jwt.controller.EmployeeController;
import com.jwt.dao.EmployeeDAO;
import com.jwt.dao.EmployeeDAOImpl;

import javafx.scene.control.Alert;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@ComponentScan(basePackages="com.jwt")
@EnableWebMvc

public class MvcConfiguration extends WebMvcConfigurerAdapter{

public void demo() {
System.out.println("in configuration...");
}

@Bean
public ViewResolver getViewResolver(){
System.out.println("in configuration...");
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;

}

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}

@Bean
public DataSource getDataSource() {
System.out.println("in datasoure");
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
dataSource.setUrl("jdbc:sqlserver://localhost:1433\\MSSQLSERVER;databaseName=Demo");
dataSource.setUsername("gcflex_user");
dataSource.setPassword("Gcas1234!");

return dataSource;
}

@Bean
public EmployeeDAO getContactDAO() {
return new EmployeeDAOImpl(getDataSource());
}

@Bean
public EmployeeController getEmployeeController() {
return new EmployeeController();

}

}

web.xml

<?xml version="1.0" encoding="ISO-8859-1" ?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">

<display-name>Spring MVC Hibernate CRUD Example</display-name>

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>


<servlet>
<servlet-name>SpringDispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value> org.springframework.web.context.support.AnnotationConfigWebApplicationContext </param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.jwt.MvcConfiguration</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>SpringDispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

<session-config>
<session-timeout>30</session-timeout>
</session-config>

</web-app>

编辑:-

EmployeeService.java

package com.jwt.service;

import java.util.List;

import com.jwt.model.Employee;

public interface EmployeeService {

public void addEmployee(Employee employee);

public List<Employee> getAllEmployees();

public void deleteEmployee(Integer employeeId);

public Employee getEmployee(int employeeid);

public Employee updateEmployee(Employee employee);
}

EmployeeServiceImpl.java

package com.jwt.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jwt.dao.EmployeeDAO;
import com.jwt.model.Employee;

@Service
@Transactional
public class EmployeeServiceImpl implements EmployeeService {

@Autowired
private EmployeeDAO employeeDAO;

@Override
@Transactional
public void addEmployee(Employee employee) {
employeeDAO.addEmployee(employee);
}

@Override
@Transactional
public List<Employee> getAllEmployees() {
return employeeDAO.getAllEmployees();
}

@Override
@Transactional
public void deleteEmployee(Integer employeeId) {
employeeDAO.deleteEmployee(employeeId);
}

public Employee getEmployee(int empid) {
return employeeDAO.getEmployee(empid);
}

public Employee updateEmployee(Employee employee) {
// TODO Auto-generated method stub
return employeeDAO.updateEmployee(employee);
}

public void setEmployeeDAO(EmployeeDAO employeeDAO) {
this.employeeDAO = employeeDAO;
}

}

错误日志:-

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.jwt.service.EmployeeService com.jwt.controller.EmployeeController.employeeService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.jwt.dao.EmployeeDAO com.jwt.service.EmployeeServiceImpl.employeeDAO; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeDAOImpl' defined in file [D:\Macron Workspace.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\SpringMVCHibernateCRUD\WEB-INF\classes\com\jwt\dao\EmployeeDAOImpl.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.jwt.dao.EmployeeDAOImpl]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.jwt.dao.EmployeeDAOImpl.() at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1202) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480) at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:663) at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:629) at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:677) at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:548) at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:489) 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:1269) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1182) at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1072) at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5362) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5660) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1700) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1690) at java.util.concurrent.FutureTask.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.jwt.service.EmployeeService com.jwt.controller.EmployeeController.employeeService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.jwt.dao.EmployeeDAO com.jwt.service.EmployeeServiceImpl.employeeDAO; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeDAOImpl' defined in file [D:\Macron Workspace.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\SpringMVCHibernateCRUD\WEB-INF\classes\com\jwt\dao\EmployeeDAOImpl.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.jwt.dao.EmployeeDAOImpl]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.jwt.dao.EmployeeDAOImpl.() at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331) ... 29 more Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.jwt.dao.EmployeeDAO com.jwt.service.EmployeeServiceImpl.employeeDAO; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeDAOImpl' defined in file [D:\Macron Workspace.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\SpringMVCHibernateCRUD\WEB-INF\classes\com\jwt\dao\EmployeeDAOImpl.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.jwt.dao.EmployeeDAOImpl]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.jwt.dao.EmployeeDAOImpl.() at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1202) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1120) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1044) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)

最佳答案

我的建议是保持简单。

  1. 从配置类中删除以下 bean 创建 -
@Bean
public EmployeeDAO getContactDAO() {
return new EmployeeDAOImpl(getDataSource());
}

@Bean
public EmployeeController getEmployeeController() {
return new EmployeeController();
}
  • 使用@Controller注释 Controller 类,使用@Service注释服务,使用@Repository注释DAO。然后,您可以轻松地在其他类中 Autowiring 它们。
  • @Repository
    public class EmployeeDAOImpl {
    }

    @Service
    public class EmployeeService {
    @Autowired
    private EmployeeDAO employeeDAO;
    }

    @Controller
    public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;
    }
  • 最后,对于您的 EmployeeDAOImpl 类,删除数据源的任何参数化构造函数。您也可以简单地 Autowiring 它,因为您已经在配置文件中为数据源创建了 @Bean -
  • @Bean
    public DataSource datasource() {
    System.out.println("in datasoure");
    return dataSource;
    }

    @Repository
    public class EmployeeDAOImpl {
    @Autowired
    private Datasource datasource;

    }

    这样您的问题就应该得到解决。

    关于java - 创建名称为 'employeeController' : Injection of autowired dependencies failed 的 bean 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48238314/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com