我是春季MVC的新手。我正在寫CRUD Spring MVC應用程序來理解Spring MVC的流程。 我收到錯誤org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'homeController': Injection of autowired dependencies failed
。org.springframework.beans.factory.BeanCreationException:創建名爲'homeController'的bean時出錯:注入自動裝配依賴失敗;
我搜索了這個錯誤的解決方案,但找不到確切的解決方案。 stackoverflow
有多個問題。但我真的不知道這個錯誤的原因是什麼,我該如何解決這個錯誤。
堆棧跟蹤
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'homeController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.varun.contact.dao.ContactDao com.varun.contact.controller.HomeController.contactDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.varun.contact.dao.ContactDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:385)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:284)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:111)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3910)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4393)
at org.jboss.web.tomcat.service.deployers.TomcatDeployment.performDeployInternal(TomcatDeployment.java:310)
at org.jboss.web.tomcat.service.deployers.TomcatDeployment.performDeploy(TomcatDeployment.java:142)
at org.jboss.web.deployers.AbstractWarDeployment.start(AbstractWarDeployment.java:461)
at org.jboss.web.deployers.WebModule.startModule(WebModule.java:118)
at org.jboss.web.deployers.WebModule.start(WebModule.java:97)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:157)
at org.jboss.mx.server.Invocation.dispatch(Invocation.java:96)
at org.jboss.mx.server.Invocation.invoke(Invocation.java:88)
at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264)
at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:668)
at org.jboss.system.microcontainer.ServiceProxy.invoke(ServiceProxy.java:206)
at com.sun.proxy.$Proxy39.start(Unknown Source)
at org.jboss.system.microcontainer.StartStopLifecycleAction.installAction(StartStopLifecycleAction.java:42)
at org.jboss.system.microcontainer.StartStopLifecycleAction.installAction(StartStopLifecycleAction.java:37)
at org.jboss.dependency.plugins.action.SimpleControllerContextAction.simpleInstallAction(SimpleControllerContextAction.java:62)
at org.jboss.dependency.plugins.action.AccessControllerContextAction.install(AccessControllerContextAction.java:71)
at org.jboss.dependency.plugins.AbstractControllerContextActions.install(AbstractControllerContextActions.java:51)
at org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:348)
at org.jboss.system.microcontainer.ServiceControllerContext.install(ServiceControllerContext.java:286)
at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:1631)
at org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:934)
at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1082)
at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:984)
at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:822)
at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:553)
at org.jboss.system.ServiceController.doChange(ServiceController.java:688)
at org.jboss.system.ServiceController.start(ServiceController.java:460)
at org.jboss.system.deployers.ServiceDeployer.start(ServiceDeployer.java:163)
at org.jboss.system.deployers.ServiceDeployer.deploy(ServiceDeployer.java:99)
at org.jboss.system.deployers.ServiceDeployer.deploy(ServiceDeployer.java:46)
at org.jboss.deployers.spi.deployer.helpers.AbstractSimpleRealDeployer.internalDeploy(AbstractSimpleRealDeployer.java:62)
at org.jboss.deployers.spi.deployer.helpers.AbstractRealDeployer.deploy(AbstractRealDeployer.java:50)
at org.jboss.deployers.plugins.deployers.DeployerWrapper.deploy(DeployerWrapper.java:171)
at org.jboss.deployers.plugins.deployers.DeployersImpl.doDeploy(DeployersImpl.java:1439)
at org.jboss.deployers.plugins.deployers.DeployersImpl.doInstallParentFirst(DeployersImpl.java:1157)
at org.jboss.deployers.plugins.deployers.DeployersImpl.doInstallParentFirst(DeployersImpl.java:1178)
at org.jboss.deployers.plugins.deployers.DeployersImpl.install(DeployersImpl.java:1098)
at org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:348)
at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:1631)
at org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:934)
at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1082)
at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:984)
at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:822)
at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:553)
at org.jboss.deployers.plugins.deployers.DeployersImpl.process(DeployersImpl.java:781)
at org.jboss.deployers.plugins.main.MainDeployerImpl.process(MainDeployerImpl.java:702)
at org.jboss.system.server.profileservice.repository.MainDeployerAdapter.process(MainDeployerAdapter.java:117)
at org.jboss.system.server.profileservice.hotdeploy.HDScanner.scan(HDScanner.java:362)
at org.jboss.system.server.profileservice.hotdeploy.HDScanner.run(HDScanner.java:255)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask.runAndReset(Unknown Source)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(Unknown Source)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.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.varun.contact.dao.ContactDao com.varun.contact.controller.HomeController.contactDao; nested exc
14:25:39,988 INFO [STDOUT] eption is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.varun.contact.dao.ContactDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:506)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
... 75 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.varun.contact.dao.ContactDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:924)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:793)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:707)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:478)
... 77 more
Contact.java
public class Contact {
\t private int id;
\t private String name;
\t private String email;
\t private String address;
\t private String telephone;
// Default Constructor
// Parameterized Constructor
//Getters and setters
\t }
的ContactDAO
public interface ContactDao {
\t
\t public void saveOrUpdate(Contact contact);
\t public void delete(int contactId);
\t public Contact get(int contactId);
\t public List<Contact> list();
}
ContactDaoImpl
public class ContactDAOImpl implements ContactDao {
\t
\t private JdbcTemplate jdbcTemplate;
\t
\t
\t public ContactDAOImpl(javax.activation.DataSource dataSource) {
\t jdbcTemplate = new JdbcTemplate((DataSource) dataSource);
\t \t
\t }
\t //Insert or update a new contact:
\t @Override
\t public void saveOrUpdate(Contact contact) {
\t \t if(contact.getId()>0){
\t \t \t //Update
\t \t \t String sql="UPDATE CONTACT SET name=?,email=?,address=?,"
\t \t \t +"telephone=? where contact_id=?";
\t \t \t System.out.println("I am inside ContactDAOImpl : save or saveOrUpdate------------------------------------------------");
\t \t \t jdbcTemplate.update(sql,contact.getName(),contact.getEmail(),contact.getAddress(),
\t \t \t \t \t contact.getTelephone(),contact.getId());
\t \t }
\t \t else{
\t \t \t // Insert
\t \t \t String sql="INSERT INTO CONTACT(name,email,address,telephone)"
\t \t \t \t \t +"VALUES(?,?,?,?)";
\t \t \t jdbcTemplate.update(sql,contact.getName(),contact.getEmail(),contact.getAddress(),
\t \t \t \t \t contact.getTelephone());
\t \t }
\t \t
\t }
\t
\t //Delete a contact:
\t @Override
\t public void delete(int contactId) {
\t String sql="DELETE FROM CONTACT where contact_id=?";
\t System.out.println("I am inside ContactDAOImpl : save or delete -----------------------------------------------------------");
\t jdbcTemplate.update(sql,contactId);
\t \t
\t }
\t //Get a particular contact:
\t @Override
\t public Contact get(int contactId) {
\t
\t \t String sql="SELECT * FROM CONTACT WHERE contact_id="+contactId;
\t \t return jdbcTemplate.query(sql, new ResultSetExtractor<Contact>() {
\t \t \t
\t \t @Override
\t \t public Contact extractData(ResultSet rs) throws SQLException,
\t \t DataAccessException {
\t \t if (rs.next()) {
\t \t Contact contact = new Contact();
\t \t contact.setId(rs.getInt("contact_id"));
\t \t contact.setName(rs.getString("name"));
\t \t contact.setEmail(rs.getString("email"));
\t \t contact.setAddress(rs.getString("address"));
\t \t contact.setTelephone(rs.getString("telephone"));
\t \t return contact;
\t \t }
\t \t
\t \t return null;
\t \t }
\t \t
\t \t });
\t }
\t
\t //List all contact:
\t @Override
\t public List<Contact> list() {
\t \t String sql = "SELECT * FROM contact";
\t \t System.out.println("I am inside List contact-------------------------- ");
\t List<Contact> listContact = jdbcTemplate.query(sql, new RowMapper<Contact>() {
\t
\t
\t @Override
\t public Contact mapRow(ResultSet rs, int rowNum) throws SQLException {
\t Contact aContact = new Contact();
\t
\t aContact.setId(rs.getInt("contact_id"));
\t aContact.setName(rs.getString("name"));
\t aContact.setEmail(rs.getString("email"));
\t aContact.setAddress(rs.getString("address"));
\t aContact.setTelephone(rs.getString("telephone"));
\t return aContact;
\t }
\t });
\t return listContact;
\t }
}
控制器類
@Controller
public class HomeController {
\t \t
\t private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
\t @Autowired
\t private ContactDao contactDao;
\t //Handler method for listing all contacts (also served as home page):
\t @RequestMapping(value = "/", method = RequestMethod.GET)
\t public ModelAndView listContact(ModelAndView model) throws IOException{
\t List<Contact> listContact = contactDao.list();
\t model.addObject("listContact", listContact);
\t model.setViewName("home");
\t return model;
}
\t //Handler method for displaying new contact form:
\t @RequestMapping(value = "/newContact", method = RequestMethod.GET)
\t public ModelAndView newContact(ModelAndView model) {
\t Contact newContact = new Contact();
\t model.addObject("contact", newContact);
\t model.setViewName("ContactForm");
\t return model;
\t }
\t
\t //Handler method for inserting/updating a contact:
\t @RequestMapping(value = "/saveContact", method = RequestMethod.POST)
\t public ModelAndView saveContact(@ModelAttribute Contact contact)
\t {
\t contactDao.saveOrUpdate(contact);
\t return new ModelAndView("redirect:/");
\t }
\t \t
\t //Handler method for retrieving details of a particular contact for editing:
\t @RequestMapping(value = "/editContact", method = RequestMethod.GET)
\t public ModelAndView editContact(HttpServletRequest request) {
\t int contactId = Integer.parseInt(request.getParameter("id"));
\t Contact contact = contactDao.get(contactId);
\t ModelAndView model = new ModelAndView("ContactForm");
\t model.addObject("contact", contact);
\t return model;
\t }
}
MVCConfiguration
package com.varun.contact.config;
@Configuration
@ComponentScan(basePackages="com.varun.contact")
@EnableWebMvc
@Repository
public class MvcConfiguration extends WebMvcConfigurerAdapter {
\t
\t @Bean
\t public ViewResolver getViewResolver(){
\t \t InternalResourceViewResolver resolver = new InternalResourceViewResolver();
\t \t resolver.setPrefix("/WEB-INF/views/");
\t \t resolver.setSuffix(".jsp");
\t return resolver;
\t }
\t
\t @Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
\t
\t @Bean
\t public DataSource getDataSource() {
\t DriverManagerDataSource dataSource = new DriverManagerDataSource();
\t dataSource.setDriverClassName("oracle.jdbc.driver.OracleDriver");
\t dataSource.setUrl("jdbc:oracle:thin:@localhost:1521:orcl");
\t dataSource.setUsername("system");
\t dataSource.setPassword("admin");
\t return (DataSource) dataSource;
\t }
\t @Bean
\t public ContactDao getContactDao() {
\t return new ContactDAOImpl(getDataSource());
\t }
}
ContactForm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>New/Edit Contact</title>
</head>
<body>
<div align="center">
<h1>New/Edit Contact</h1>
<form:form action="saveContact" method="post" modelAttribute="contact">
<table>
<tr>
<td>Id:</td>
<td><form:input path="id" /></td>
</tr>
<tr>
<td>Name:</td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td>Email:</td>
<td><form:input path="email" /></td>
</tr>
<tr>
<td>Address:</td>
<td><form:input path="address" /></td>
</tr>
<tr>
<td>Telephone:</td>
<td><form:input path="telephone" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Save"></td>
</tr>
</table>
</form:form>
</div>
</body>
</html>
回到Home.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
\t <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Contact Manager Home</title>
</head>
<body>
<h1>
\t Welcome..............................
</h1>
<P> The time on the server is ${serverTime}. </P>
<div align="center">
<h1>Contact List</h1>
<h3><a href="/newContact">New Contact</a></h3>
<table border="1">
<th>No</th>
<th>Name</th>
<th>Email</th>
<th>Address</th>
<th>Telephone</th>
<th>Action</th>
<c:forEach var="contact" items="${listContact}" varStatus="status">
<tr>
<td>${status.index + 1}</td>
<td>${contact.name}</td>
<td>${contact.email}</td>
<td>${contact.address}</td>
<td>${contact.telephone}</td>
<td>
<a href="/editContact?id=${contact.id}">Edit</a>
<a href="/deleteContact?id=${contact.id}">Delete</a>
</td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>
網絡。XML
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
\t xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
\t xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
\t <!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
\t <welcome-file-list>
\t <welcome-file>ContactForm.jsp</welcome-file>
\t </welcome-file-list>
\t
\t
\t <context-param>
\t \t <param-name>contextConfigLocation</param-name>
\t \t <param-value>/WEB-INF/spring/servlet-context.xml</param-value>
\t </context-param>
\t
\t <!-- Creates the Spring Container shared by all Servlets and Filters -->
\t <listener>
\t \t <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
\t </listener>
\t <!-- Processes application requests -->
\t <servlet>
\t \t <servlet-name>DispatcherServlet</servlet-name>
\t \t <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
\t \t <init-param>
\t \t \t <param-name>contextConfigLocation</param-name>
\t \t \t <param-value>/WEB-INF/spring/servlet-context.xml</param-value>
\t \t </init-param>
\t \t <load-on-startup>1</load-on-startup>
\t </servlet>
\t \t
\t <servlet-mapping>
\t \t <servlet-name>DispatcherServlet</servlet-name>
\t \t <url-pattern>/</url-pattern>
\t </servlet-mapping>
\t
\t <listener>
\t \t <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
\t </listener>
</web-app>
請幫我我真的無法理解什麼是錯的這個
如果沒有添加 –