创建“服务”bean 时出错
Posted
技术标签:
【中文标题】创建“服务”bean 时出错【英文标题】:Error creating "Service" bean 【发布时间】:2014-12-12 15:12:25 【问题描述】:我对服务 bean 定义有疑问。我试图调试代码,而 sessionFactory 总是为空。谁能解释一下,错误在哪里?日志:
Dec 12, 2014 5:36:10 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@62a83610: startup date [Fri Dec 12 17:36:10 FET 2014]; root of context hierarchy
Dec 12, 2014 5:36:10 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [application-context.xml]
Dec 12, 2014 5:36:10 PM org.springframework.beans.factory.support.DefaultListableBeanFactory registerBeanDefinition
INFO: Overriding bean definition for bean 'dao': replacing [Generic bean: class [com.pancerz.server.dao.impl.DaoImpl]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [/home/eugen/projects/pancerz/pancerz-server/server-admin/target/classes/com/pancerz/server/dao/impl/DaoImpl.class]] with [Generic bean: class [com.pancerz.server.dao.impl.DaoImpl]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in class path resource [application-context.xml]]
Dec 12, 2014 5:36:10 PM org.springframework.beans.factory.support.DefaultListableBeanFactory registerBeanDefinition
INFO: Overriding bean definition for bean 'userDao': replacing [Generic bean: class [com.pancerz.server.dao.impl.UserDaoImpl]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [/home/eugen/projects/pancerz/pancerz-server/server-admin/target/classes/com/pancerz/server/dao/impl/UserDaoImpl.class]] with [Generic bean: class [com.pancerz.server.dao.impl.UserDaoImpl]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in class path resource [application-context.xml]]
Dec 12, 2014 5:36:10 PM org.springframework.beans.factory.support.DefaultListableBeanFactory registerBeanDefinition
INFO: Overriding bean definition for bean 'userService': replacing [Generic bean: class [com.pancerz.server.service.impl.UserServiceImpl]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [/home/eugen/projects/pancerz/pancerz-server/server-admin/target/classes/com/pancerz/server/service/impl/UserServiceImpl.class]] with [Generic bean: class [com.pancerz.server.service.impl.UserServiceImpl]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in class path resource [application-context.xml]]
Dec 12, 2014 5:40:55 PM org.springframework.beans.factory.config.PropertyPlaceholderConfigurer loadProperties
INFO: Loading properties file from class path resource [jdbc.properties]
Dec 12, 2014 5:41:14 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@64ad8f2b: defining beans [dao,userDao,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,userService,transactionManager,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,propertyConfigurer,dataSource,sessionFactory,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy
Dec 12, 2014 5:42:07 PM org.springframework.jdbc.datasource.DriverManagerDataSource setDriverClassName
INFO: Loaded JDBC driver: com.mysql.jdbc.jdbc2.optional.MysqlDataSource
Dec 12, 2014 5:42:13 PM org.hibernate.annotations.common.Version <clinit>
INFO: HCANN000001: Hibernate Commons Annotations 4.0.2.Final
Dec 12, 2014 5:42:13 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core 4.2.16.Final
Dec 12, 2014 5:42:13 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Dec 12, 2014 5:42:13 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Dec 12, 2014 5:42:19 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Dec 12, 2014 5:42:20 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Dec 12, 2014 5:42:20 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Dec 12, 2014 5:53:56 PM org.springframework.beans.factory.support.DefaultListableBeanFactory destroySingletons
INFO: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@64ad8f2b: defining beans [dao,userDao,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,userService,transactionManager,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,propertyConfigurer,dataSource,sessionFactory,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userService' defined in class path resource [application-context.xml]: Initialization of bean failed; nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'com.sun.proxy.$Proxy11 implementing com.pancerz.server.dao.UserDao,com.pancerz.server.dao.Dao,org.springframework.aop.SpringProxy,org.springframework.aop.framework.Advised' to required type 'com.pancerz.server.dao.impl.UserDaoImpl' for property 'userDao'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [com.sun.proxy.$Proxy11 implementing com.pancerz.server.dao.UserDao,com.pancerz.server.dao.Dao,org.springframework.aop.SpringProxy,org.springframework.aop.framework.Advised] to required type [com.pancerz.server.dao.impl.UserDaoImpl] for property 'userDao': no matching editors or conversion strategy found
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:529)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:296)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:293)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:628)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at MainTest.main(MainTest.java:13)
Caused by: org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'com.sun.proxy.$Proxy11 implementing com.pancerz.server.dao.UserDao,com.pancerz.server.dao.Dao,org.springframework.aop.SpringProxy,org.springframework.aop.framework.Advised' to required type 'com.pancerz.server.dao.impl.UserDaoImpl' for property 'userDao'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [com.sun.proxy.$Proxy11 implementing com.pancerz.server.dao.UserDao,com.pancerz.server.dao.Dao,org.springframework.aop.SpringProxy,org.springframework.aop.framework.Advised] to required type [com.pancerz.server.dao.impl.UserDaoImpl] for property 'userDao': no matching editors or conversion strategy found
at org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:463)
at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:494)
at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:488)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.convertForProperty(AbstractAutowireCapableBeanFactory.java:1463)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1422)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1158)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
... 11 more
Caused by: java.lang.IllegalStateException: Cannot convert value of type [com.sun.proxy.$Proxy11 implementing com.pancerz.server.dao.UserDao,com.pancerz.server.dao.Dao,org.springframework.aop.SpringProxy,org.springframework.aop.framework.Advised] to required type [com.pancerz.server.dao.impl.UserDaoImpl] for property 'userDao': no matching editors or conversion strategy found
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:267)
at org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:448)
... 17 more
application-context.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:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.pancerz.server.dao" />
<context:component-scan base-package="com.pancerz.server.service" />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="jdbc.properties"/>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"
value="com.mysql.jdbc.jdbc2.optional.MysqlDataSource"/>
<property name="url" value="jdbc:mysql://localhost/server-admin_dev"/>
<property name="username" value="root"/>
<property name="password" value="password"/>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.connection.charSet">UTF-8</prop>
</props>
</property>
</bean>
<bean id="dao" class="com.pancerz.server.dao.impl.DaoImpl">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="userDao" class="com.pancerz.server.dao.impl.UserDaoImpl" parent="dao">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="userService" class="com.pancerz.server.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"/>
</bean>
</beans>
Dao.java
public interface Dao<T, PK extends Serializable>
public PK save(T newInstance);
public void update(T transientObject);
public List<T> findAll();
public List<T> findByCriteria(Criterion... criterion);
public T findById(PK id);
public void delete(PK id);
public void delete(T persistentObject);
DaoImpl.java
@Repository("dao")
@Transactional(propagation= Propagation.REQUIRED, readOnly=false)
public class DaoImpl<T, PK extends Serializable> implements Dao<T, PK>
SessionFactory sessionFactory;
private Class<T> entityClass;
public DaoImpl()
public DaoImpl(Class<T> clazz)
this.entityClass = clazz;
@SuppressWarnings("unchecked")
@Override
public PK save(T newInstance)
return (PK) getSession().save(newInstance);
@SuppressWarnings("unchecked")
@Override
public void update(T transientObject)
getSession().update(transientObject);
@SuppressWarnings("unchecked")
@Override
public List<T> findAll()
Criteria criteria = getSession().createCriteria(entityClass);
return (List<T>) criteria.list();
@SuppressWarnings("unchecked")
@Override
public List<T> findByCriteria(Criterion... criterion)
Criteria criteria = getSession().createCriteria(entityClass);
for (Criterion c : criterion)
criteria.add(c);
return (List<T>) criteria.list();
@SuppressWarnings("unchecked")
@Override
public T findById(PK id)
return (T) getSession().get(entityClass, id);
@SuppressWarnings("unchecked")
@Override
public void delete(PK id)
T persistentObject = (T) getSession().load(entityClass, id);
try
getSession().delete(persistentObject);
catch (NonUniqueObjectException e)
T instance = (T) getSession().merge(persistentObject);
getSession().delete(instance);
@SuppressWarnings("unchecked")
@Override
public void delete(T persistentObject)
try
getSession().delete(persistentObject);
catch (NonUniqueObjectException e)
T instance = (T) getSession().merge(persistentObject);
getSession().delete(instance);
protected Session getSession()
return sessionFactory.getCurrentSession();
@Autowired
public void setSessionFactory(SessionFactory sessionFactory)
this.sessionFactory = sessionFactory;
UserDao.java
public interface UserDao extends Dao<User, Long>
public User findByLogin(String login);
public User createUser(String login, String password, String email, String name, String surName,
Date birthDay, Date registrationDate, int role);
UserDaoImpl.java
package com.pancerz.server.dao.impl;
import com.pancerz.server.dao.UserDao;
import com.pancerz.server.models.User;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
/**
* Date: 12/12/14
*/
@Repository("userDao")
public class UserDaoImpl extends DaoImpl<User, Long> implements UserDao
public UserDaoImpl()
super(User.class);
@Override
@Transactional
public User findByLogin(String login)
Criteria criteria = getSession().createCriteria(User.class);
criteria.add(Restrictions.like("login", login));
return (User) criteria.uniqueResult();
@Override
public User createUser(String login, String password, String email, String name, String surName,
Date birthDay, Date registrationDate, int role)
Criteria criteria = getSession().createCriteria(User.class);
// criteria.set
return (User) criteria.uniqueResult();
UserService.java
package com.pancerz.server.service;
import com.pancerz.server.models.User;
import java.util.List;
/**
* Date: 12/12/14
*/
public interface UserService
public User findByLogin(String login);
public List<User> getAllUsers();
UserServiceImpl.java
@Service("userService")
public class UserServiceImpl implements UserService
private UserDaoImpl userDao;
public UserServiceImpl()
@Override
@Transactional
public User findByLogin(String login)
return userDao.findByLogin(login);
@Override
@Transactional
public List<User> getAllUsers()
return userDao.findAll();
@Autowired
public void setUserDao(UserDaoImpl userDao)
this.userDao = userDao;
【问题讨论】:
【参考方案1】:您在 UserServiceImpl 类中使用了 UserDaoImpl,但是通过实现 UserDao 接口来代理该类。
将 UserDaoImpl 类型更改为 UserDao 并在 setter 中更改它,它应该可以工作。
【讨论】:
谢谢,它有帮助,但我仍然无法从数据库中得到结果 我试过这个: public class MainTest public static void main(String[] args) ApplicationContext context = new ClassPathXmlApplicationContext("application -context.xml"); context.getBean("userService"); UserDao userDao = (UserDao) context.getBean("userDao");用户用户 = userDao.findByLogin("eugen");列表 用户 = userDao.findAll();结果是空的,不明白为什么。 这是另一个问题。接受这个并开始一个新的。以上是关于创建“服务”bean 时出错的主要内容,如果未能解决你的问题,请参考以下文章
创建名为“requestMappingHandlerAdapter”的 bean 时出错
创建名为“activityController”的 bean 时出错
创建名为“entityManagerFactoryBean”的bean时出错
创建 ApplicationContext.xml 中定义的 bean 时出错