我使用Spring 3和Hibernate 4.我是这个概念的新手,并且已经做了一些阅读和学习。我找到了GenericDAO Layer和GenericService Layer的示例实现。这是我的代码:
这是AbstractDao界面:
package dao.api;
public interface IAbstractDAO<T, PK extends Serializable> {
/** Persist the newInstance object into database */
public PK create(T newInstance);
/**
* Retrieve an object that was previously persisted to the database using
* the indicated id as primary key
*/
public T findById(PK id);
/**Get all Object from db */
public List<T> listAll();
/** Save changes made to a persistent object. */
public void update(T transientObject);
/** Remove an object from persistent storage in the database */
public void delete(T persistentObject);
}
这是我的AbstractDAOImpl类:
package dao;
@Transactional
public abstract class AbstractDAOImpl<T, PK extends Serializable> implements
IAbstractDAO<T, PK> {
private Class<T> type;
public AbstractDAOImpl(Class<T> type) {
this.type = type;
}
@Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
protected Session getCurrentSession() {
// if (sessionFactory == null)
// throw new IllegalStateException(
// "SessionFactory has not been set on DAO before usage");
return sessionFactory.getCurrentSession();
}
@SuppressWarnings("unchecked")
@Override
public PK create(T newInstance) {
return (PK) getCurrentSession().save(newInstance);
}
@SuppressWarnings("unchecked")
@Override
public T findById(PK id) {
return (T) getCurrentSession().get(type, id);
}
@SuppressWarnings("unchecked")
@Override
public List<T> listAll() {
Criteria criteria = getCurrentSession().createCriteria(type);
return criteria.list();
}
@Override
public void update(T transientObject) {
getCurrentSession().update(transientObject);
}
@Override
public void delete(T persistentObject) {
getCurrentSession().delete(persistentObject);
}
}
这是我的IUserDAO界面:
package dao.api;
public interface IUserDAO extends IAbstractDAO<User,Integer> {
}
这是我的UserDAOImpl类:
package tma.com.ntrungnghia.dao;
import org.springframework.stereotype.Repository;
import tma.com.ntrungnghia.dao.api.IUserDAO;
import tma.com.ntrungnghia.domain.User;
@Repository("userDAO")
public class UserDAOImpl extends AbstractDAOImpl<User, Integer> implements IUserDAO{
public UserDAOImpl() {
super(User.class);
}
}
在服务层,我有IAbstractService接口
package service.api;
public interface IAbstractService<T, PK extends Serializable > {
/** Persist the newInstance object into database */
public PK create(T newInstance);
/**
* Retrieve an object that was previously persisted to the database using
* the indicated id as primary key
*/
public T findById(PK id);
/**Get all Object from db */
public List<T> listAll();
/** Save changes made to a persistent object. */
public void update(T transientObject);
/** Remove an object from persistent storage in the database */
public void delete(T persistentObject);
}
这是AbstractServiceImpl类:
package service;
import java.io.Serializable;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import tma.com.ntrungnghia.dao.api.IAbstractDAO;
import tma.com.ntrungnghia.service.api.IAbstractService;
public abstract class AbstractServiceImpl<T,PK extends Serializable> implements IAbstractService<T, PK> {
@Autowired
protected IAbstractDAO<T, PK> dao;
@Override
public PK create(T newInstance) {
return dao.create(newInstance);
}
@Override
public T findById(PK id) {
// TODO Auto-generated method stub
return dao.findById(id);
}
@Override
public List<T> listAll() {
// TODO Auto-generated method stub
return dao.listAll();
}
@Override
public void update(T transientObject) {
dao.update(transientObject);
}
@Override
public void delete(T persistentObject) {
dao.delete(persistentObject);
}
}
这是我的IUserService接口:
package service.api;
public interface IUserService extends IAbstractService<User, Integer>{
}
和UserService接口的实现:
package service;
@Service("userService")
public class UserServiceImpl extends AbstractServiceImpl<User, Integer> implements IUserService{
}
这是我的控制器:
@Controller
public class HomeController {
@Autowired
IUserService userService;
@Autowired
IOrderService orderService;
@Autowired
IOrderDeitalService orderDeitalService;
@Autowired
IAlbumService albumService;
@Autowired
IGenreService genreService;
@Autowired
IArtistService artistService;
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
/**
* Simply selects the home view to render by returning its name.
*/
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate );
User u = new User();
userService.create(u);
return "home";
}
}
Spring配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
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">
<!-- Root Context: defines shared resources visible to all other web components -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="url" value="jdbc:mysql://localhost:3306/musicstore"></property>
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
</bean>
<bean id="sessionFactory" name="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect"> org.hibernate.dialect.MySQLDialect </prop>
<prop key="hibernate.max_fetch_depth">3</prop>
<prop key="hibernate.jdbc.fetch_size">50</prop>
<prop key="hibernate.jdbc.batch_size">10</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="packagesToScan" value="domain" /><!-- entity -->
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
<property name="dataSource" ref="dataSource" />
</bean>
<context:component-scan base-package="dao" />
<context:component-scan base-package="service" />
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
这是我运行项目时得到的结果
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'albumService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: protected tma.com.ntrungnghia.dao.api.IAbstractDAO tma.com.ntrungnghia.service.AbstractServiceImpl.dao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [tma.com.ntrungnghia.dao.api.IAbstractDAO] is defined: expected single matching bean but found 6: [albumDAO, artistDAO, genreDAO, orderDAO, orderDetailDAO, userDAO]
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:4973)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5467)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:632)
at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:670)
at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1839)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
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: protected tma.com.ntrungnghia.dao.api.IAbstractDAO tma.com.ntrungnghia.service.AbstractServiceImpl.dao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [tma.com.ntrungnghia.dao.api.IAbstractDAO] is defined: expected single matching bean but found 6: [albumDAO, artistDAO, genreDAO, orderDAO, orderDetailDAO, userDAO]
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)
... 26 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [tma.com.ntrungnghia.dao.api.IAbstractDAO] is defined: expected single matching bean but found 6: [albumDAO, artistDAO, genreDAO, orderDAO, orderDetailDAO, userDAO]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:800)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:707)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:478)
... 28 more
Oct 08, 2014 4:41:34 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'albumService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: protected tma.com.ntrungnghia.dao.api.IAbstractDAO tma.com.ntrungnghia.service.AbstractServiceImpl.dao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [tma.com.ntrungnghia.dao.api.IAbstractDAO] is defined: expected single matching bean but found 6: [albumDAO, artistDAO, genreDAO, orderDAO, orderDetailDAO, userDAO]
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:4973)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5467)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:632)
at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:670)
at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1839)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
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: protected tma.com.ntrungnghia.dao.api.IAbstractDAO tma.com.ntrungnghia.service.AbstractServiceImpl.dao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [tma.com.ntrungnghia.dao.api.IAbstractDAO] is defined: expected single matching bean but found 6: [albumDAO, artistDAO, genreDAO, orderDAO, orderDetailDAO, userDAO]
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)
... 26 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [tma.com.ntrungnghia.dao.api.IAbstractDAO] is defined: expected single matching bean but found 6: [albumDAO, artistDAO, genreDAO, orderDAO, orderDetailDAO, userDAO]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:800)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:707)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:478)
... 28 more
我对albumDAO,artistDAO,genreDAO,orderDAO,orderDetailDAO和这些服务做了同样的事情。
当我使用AbstractService中定义的create方法时,它不起作用。我不明白。如果有人可以帮助我?
提前感谢您的想法和回应!