我遇到以下异常,请帮忙解决此问题?
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.dao.UserDAO com.controller.UserController.userDAO; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDAOImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.dao.UserDAOImpl.sessionFactory; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [org.hibernate.SessionFactory] 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)}
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:609)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:469)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:631)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:588)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:645)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:508)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:449)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:133)
javax.servlet.GenericServlet.init(GenericServlet.java:160)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
java.lang.Thread.run(Unknown Source)
root cause
org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.dao.UserDAO com.controller.UserController.userDAO; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDAOImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.dao.UserDAOImpl.sessionFactory; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [org.hibernate.SessionFactory] 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)}
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:506)
org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:609)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:469)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:631)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:588)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:645)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:508)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:449)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:133)
javax.servlet.GenericServlet.init(GenericServlet.java:160)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
java.lang.Thread.run(Unknown Source)
各自的java代码如下 - 的 UserDAO的
package com.dao;
import java.util.List;
import com.entity.UserDetails;
public interface UserDAO {
public List<UserDetails> getUserProfileDetails();
public int saveUserDetails(UserDetails userDetails);
public UserDetails authenticateUser(String email,String password);
public void closeSessionObjects();
}
在UserDAOImpl
package com.dao;
import java.util.List;
import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.dao.UserDAO;
import com.entity.UserDetails;
@Component
@Transactional(readOnly = true)
public class UserDAOImpl implements UserDAO {
private static Logger logger = Logger.getLogger(UserDAOImpl.class);
@Autowired
private SessionFactory sessionFactory;
Session session = null;
private void assignSessionLocalVariable(){
if(session == null || !session.isOpen()){
try{
session = sessionFactory.openSession();
}catch(Exception e){session = null;}
}
}
@Override
public List<UserDetails> getUserProfileDetails() {
List<UserDetails> details=null;
if(session!=null){
try{
Query query = session.createQuery("from user");
details = query.list();
}catch(Exception e)
{
logger.error("########### Exception occured ########## "+e+" ");
}
}
return details;
}
@Override
public int saveUserDetails(UserDetails userDetails){
int saved=1;
assignSessionLocalVariable();
try{
Transaction tx=session.beginTransaction();
session.save(userDetails);
tx.commit();
saved=0;
logger.info("#### Details saved successfuly #####");
}catch(Exception e){
logger.error("### Exception occured in UserDAOImpl class #### "+e+"");
}
return saved;
}
@Override
public UserDetails authenticateUser(String email, String pwd) {
// TODO Auto-generated method stub
System.out.println("##### UserDAOImple authenticateuser started #####");
assignSessionLocalVariable();
logger.info("### Authentication of the user in progress ####");
UserDetails users = null;
if(session!=null){
try{
Query qry = session.createQuery ("from user hu where hu.email = :email and hu.password = :password");
qry.setParameter ("email", email);
qry.setParameter ("password", pwd);
qry.setMaxResults(1);
users = (UserDetails)qry.uniqueResult();
}catch(Exception e){
users = null;
System.out.println("UserDAOImpl exception in getting unique result["+e+"] ");
logger.error("UserDAOImpl exception in getting unique result["+e+"]");
}
}//if(session!=null)
return users;
}
public void closeSessionObjects(){
if(null != session) session.clear();//close();
//if(null != sessionFactory) sessionFactory.close();
}
}
UsedDetails.java
package com.entity;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity
@Table(name="user",catalog="test")
public class UserDetails implements java.io.Serializable{
private int id;
private String firstName;
private String lastName;
private int age;
private Date creationTime;
private Date lastModTime;
private String password;
private String email;
public UserDetails(){}
public UserDetails(String email){
this.email=email;
}
@Id
@Column(name="ID", unique = true, nullable = false)
public int getId() {
return id;
}
public void setId(int id){
this.id = id;
}
@Column(name="FIRST_NAME")
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
@Column(name="LAST_NAME")
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Column(name="AGE")
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "CREATION_TIME", nullable = false, length = 19)
public Date getCreationTime() {
return creationTime;
}
public void setCreationTime(Date creationTime) {
this.creationTime = creationTime;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "LAST_MOD_TIME", nullable = false, length = 19)
public Date getLastModTime() {
return lastModTime;
}
public void setLastModTime(Date lastModTime) {
this.lastModTime = lastModTime;
}
@Column(name="PASSWORD")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Column(name="EMAIL")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
UserController.java
package com.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.dao.UserDAO;
import com.entity.UserDetails;
@Controller
public class UserController {
private static Logger logger = Logger.getLogger(UserController.class);
String errForward = "user.error", forward = null;
@Autowired
UserDAO userDAO;
@Autowired
UserDetails ud=null;;
@RequestMapping("/register")
public ModelAndView registerPage() {
logger.info("## Registration page forward #####");
return new ModelAndView("user.registration");
}
@RequestMapping("/registerUser")
public ModelAndView registerUser(HttpServletRequest request) {
logger.info("### Inside registeration controller ####");
int isSave=0;
Date creation_time=null,lastModTime=null;
String fName=request.getParameter("fName");
fName=(fName.equals(""))?"":fName.trim();
String lName=request.getParameter("lName");
lName=(lName.equals(""))?"":lName.trim();
int age=Integer.parseInt(request.getParameter("age"));
age=(age==0)?0:age;
String email=request.getParameter("email");
email=(email.equals(""))?"":email.trim();
String pswd=request.getParameter("pswd");
pswd=(pswd.equals(""))?"":pswd.trim();
Date date=new Date();
//creation_time=dt.getDate();
ud.setFirstName(fName);
ud.setLastName(lName);
ud.setAge(age);
ud.setPassword(pswd);
ud.setEmail(email);
ud.setCreationTime(creation_time);
ud.setLastModTime(lastModTime);
try{
isSave=userDAO.saveUserDetails(ud);
if (isSave==0){
System.out.println("%%% Successfully saved the user ::::"+isSave);
logger.info("Successfully saved the data :::"+isSave);
forward="user.registrationUserSuccess";
}
}catch(Exception e){
logger.error("##### Error while saving use details #####"+e);
return new ModelAndView(forward);
}
return new ModelAndView(forward);
}
@RequestMapping("/login")
public ModelAndView addStudent(HttpServletRequest request) {
logger.info("### Login in progress ####");
String email=request.getParameter("email");
email=(email.equals(""))?"":email.trim();
String pswd=request.getParameter("pswd");
pswd=(pswd.equals(""))?"":pswd.trim();
String login=request.getParameter("login");
login = (null != login)?login:"";
logger.info("### User login for ::: ["+email+"]:::: ######");
HttpSession httpSession = request.getSession();
if(null!=login)ud= userDAO.authenticateUser(email, pswd);
if(null!=ud){
httpSession.setAttribute("isActiveUser", ud);
forward = "user.profile";
}else forward = errForward;
return new ModelAndView(forward);
}
}
的web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:web="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" id="WebApp_ID" version="2.4">
<display-name>Spring User</display-name>
<servlet>
<servlet-name>User</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>User</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/jsp/home.jsp</welcome-file>
</welcome-file-list>
<session-config>
<session-timeout>60</session-timeout>
</session-config>
</web-app>
用户-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:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
<mvc:annotation-driven/>
<context:annotation-config/>
<context:component-scan base-package="com.controller" />
<context:component-scan base-package="com.dao" />
<context:component-scan base-package="com.entity" />
<!-- title defining -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass">
<value>
org.springframework.web.servlet.view.tiles2.TilesView
</value>
</property>
</bean>
<!-- defining title file location -->
<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
<import resource="db-config.xml" />
</beans>
分贝-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"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<bean id="dbPropertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>/WEB-INF/configuration.properties</value>
</list>
</property>
</bean>
<!-- Database Properties -->
<bean id="dataSource"
class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"
p:driverClass="${jdbc.driver.className}"
p:jdbcUrl="${jdbc.url}"
p:user="${jdbc.username}"
p:password="${jdbc.password}"
/>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.hibernate.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="packagesToScan" value="com.entity" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
当我尝试运行此代码时,我发现了我发布的异常。自动注射没有发生。有什么问题?
答案 0 :(得分:0)
仔细看看例外,它说
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency.
看起来你没有创建sessionFactory
bean。确保在弹簧配置中添加了sessionFactory
例如:
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
p:dataSource-ref="dataSource"
p:configLocation="${hibernate.config}"
/>