我是春季MVC的新手。我正在编写CRUD Spring MVC应用程序来了解spring MVC的流程。
我收到错误org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'homeController': Injection of autowired dependencies failed
。
我搜索了此错误的解决方案但无法找到确切的解决方案。 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 {
private int id;
private String name;
private String email;
private String address;
private String telephone;
// Default Constructor
// Parameterized Constructor
//Getters and setters
}
的ContactDAO
public interface ContactDao {
public void saveOrUpdate(Contact contact);
public void delete(int contactId);
public Contact get(int contactId);
public List<Contact> list();
}
ContactDaoImpl
public class ContactDAOImpl implements ContactDao {
private JdbcTemplate jdbcTemplate;
public ContactDAOImpl(javax.activation.DataSource dataSource) {
jdbcTemplate = new JdbcTemplate((DataSource) dataSource);
}
//Insert or update a new contact:
@Override
public void saveOrUpdate(Contact contact) {
if(contact.getId()>0){
//Update
String sql="UPDATE CONTACT SET name=?,email=?,address=?,"
+"telephone=? where contact_id=?";
System.out.println("I am inside ContactDAOImpl : save or saveOrUpdate------------------------------------------------");
jdbcTemplate.update(sql,contact.getName(),contact.getEmail(),contact.getAddress(),
contact.getTelephone(),contact.getId());
}
else{
// Insert
String sql="INSERT INTO CONTACT(name,email,address,telephone)"
+"VALUES(?,?,?,?)";
jdbcTemplate.update(sql,contact.getName(),contact.getEmail(),contact.getAddress(),
contact.getTelephone());
}
}
//Delete a contact:
@Override
public void delete(int contactId) {
String sql="DELETE FROM CONTACT where contact_id=?";
System.out.println("I am inside ContactDAOImpl : save or delete -----------------------------------------------------------");
jdbcTemplate.update(sql,contactId);
}
//Get a particular contact:
@Override
public Contact get(int contactId) {
String sql="SELECT * FROM CONTACT WHERE contact_id="+contactId;
return jdbcTemplate.query(sql, new ResultSetExtractor<Contact>() {
@Override
public Contact extractData(ResultSet rs) throws SQLException,
DataAccessException {
if (rs.next()) {
Contact contact = new Contact();
contact.setId(rs.getInt("contact_id"));
contact.setName(rs.getString("name"));
contact.setEmail(rs.getString("email"));
contact.setAddress(rs.getString("address"));
contact.setTelephone(rs.getString("telephone"));
return contact;
}
return null;
}
});
}
//List all contact:
@Override
public List<Contact> list() {
String sql = "SELECT * FROM contact";
System.out.println("I am inside List contact-------------------------- ");
List<Contact> listContact = jdbcTemplate.query(sql, new RowMapper<Contact>() {
@Override
public Contact mapRow(ResultSet rs, int rowNum) throws SQLException {
Contact aContact = new Contact();
aContact.setId(rs.getInt("contact_id"));
aContact.setName(rs.getString("name"));
aContact.setEmail(rs.getString("email"));
aContact.setAddress(rs.getString("address"));
aContact.setTelephone(rs.getString("telephone"));
return aContact;
}
});
return listContact;
}
}
控制器类
@Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
@Autowired
private ContactDao contactDao;
//Handler method for listing all contacts (also served as home page):
@RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView listContact(ModelAndView model) throws IOException{
List<Contact> listContact = contactDao.list();
model.addObject("listContact", listContact);
model.setViewName("home");
return model;
}
//Handler method for displaying new contact form:
@RequestMapping(value = "/newContact", method = RequestMethod.GET)
public ModelAndView newContact(ModelAndView model) {
Contact newContact = new Contact();
model.addObject("contact", newContact);
model.setViewName("ContactForm");
return model;
}
//Handler method for inserting/updating a contact:
@RequestMapping(value = "/saveContact", method = RequestMethod.POST)
public ModelAndView saveContact(@ModelAttribute Contact contact)
{
contactDao.saveOrUpdate(contact);
return new ModelAndView("redirect:/");
}
//Handler method for retrieving details of a particular contact for editing:
@RequestMapping(value = "/editContact", method = RequestMethod.GET)
public ModelAndView editContact(HttpServletRequest request) {
int contactId = Integer.parseInt(request.getParameter("id"));
Contact contact = contactDao.get(contactId);
ModelAndView model = new ModelAndView("ContactForm");
model.addObject("contact", contact);
return model;
}
}
MVCConfiguration
package com.varun.contact.config;
@Configuration
@ComponentScan(basePackages="com.varun.contact")
@EnableWebMvc
@Repository
public class MvcConfiguration extends WebMvcConfigurerAdapter {
@Bean
public ViewResolver getViewResolver(){
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() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("oracle.jdbc.driver.OracleDriver");
dataSource.setUrl("jdbc:oracle:thin:@localhost:1521:orcl");
dataSource.setUsername("system");
dataSource.setPassword("admin");
return (DataSource) dataSource;
}
@Bean
public ContactDao getContactDao() {
return new ContactDAOImpl(getDataSource());
}
}
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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Contact Manager Home</title>
</head>
<body>
<h1>
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>
Web.xml中
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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_2_5.xsd">
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<welcome-file-list>
<welcome-file>ContactForm.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/servlet-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
请帮助我,我真的无法理解这个
有什么问题答案 0 :(得分:0)
看起来在控制器中注入ContactDAO的问题。
使用@Repository注释标记您的ContactDAOImpl,并检查ContactDAOImpl所在的包是否包含在您的配置的scan
中
答案 1 :(得分:0)
你需要告诉Spring从中获取bean的位置。要做到这一点:
ContactDAOImpl
@Repository
在xml配置中添加一行:
<context:component-scan base-package="dao packagename" />
通过这样做,您指的是需要从中拾取bean的位置。