##context.xml ##
<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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<bean id="hiberDataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/DB" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="hiberDataSource"/>
<property name="annotatedClasses">
<list>
<value>com.basemodel.model.Ground</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean name="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
<context:annotation-config />
<tx:annotation-driven transaction-manager="transactionManager" />
<context:component-scan base-package="com.basemodel.dao, com.basemodel.model" />
</bean>
</beans>
## DAO课程:## package com.basemodel.dao;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.basemodel.model.Ground;
import com.basemodel.model.NewsFeed;
@Component
public class FeedListDAO {
@Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory)
{
this.sessionFactory = sessionFactory;
}
public List<NewsFeed> getNewsFeed() {
List<NewsFeed> feedList = new ArrayList<NewsFeed>();
for (int i = 0; i < 6; i++) {
NewsFeed feed = new NewsFeed();
feed.setPostedby("" + i);
feed.setMediaType("TEXT");
feed.setPostContentMessage("We are part of the CB");
feedList.add(feed);
}
Ground ground = new Ground();
ground.setArea("Medavakkam");
Session session = sessionFactory.openSession();
session.persist(ground);
//getHibernateTemplate().save(ground);
return feedList;
}
}
##说明:## 我正在使用Spring mvc,multimodule maven项目,我的每个模块都有单独的spring上下文配置文件,并使用contextconfiglocation类路径加载它们:context.xml(每个模块中的所有配置文件都命名为context.xml)
Am getting an error while tomcat is starting up only when I am looking to wire the hibernate session factory, if I remove the same in my DAO, tomcat is starting up the rest call is getting inside.
## error details ##
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 'feedListDAO': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.basemodel.dao.FeedListDAO.sessionFactory; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying 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)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:444)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:326)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4812)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5255)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
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: private org.hibernate.SessionFactory com.basemodel.dao.FeedListDAO.sessionFactory; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying 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)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:573)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 22 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying 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)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1373)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1119)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:545)
... 24 more
答案 0 :(得分:0)
稍微重新设计您的BASEDAO课程
请创建一个构造函数参数来设置SessionFactory,如下所示
@Autowired
public FeedListDAO(SessionFactory sessionFactory) {
super(YourModel.class);
super.setSessionFactory(sessionFactory);
}
您应该像下面的示例一样定义您的BASEDAO。
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import org.hibernate.SessionFactory;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.orm.hibernate3.HibernateTemplate;
import com.XX.XXXXIBaseDAO;
/**
* Base class for all hibernate DAO implementations
* extend this class only when your require custom CRUD logic.
*
* @param <T> a type variable
* @param <PK> the primary key for that type
*/
@SuppressWarnings("unchecked")
public class BaseDAOImpl<T, PK extends Serializable> implements IBaseDAO<T, PK> {
/**
* Log variable for all child classes.
*/
private final Class<T> persistentClass;
private HibernateTemplate hibernateTemplate;
private SessionFactory sessionFactory;
/**
* Constructor that takes in a class to see which type of entity to persist.
* Use this constructor when subclassing.
*
* @param persistentClass the class type you'd like to persist
*/
public BaseDAOImpl(final Class<T> persistentClass) {
this.persistentClass = persistentClass;
}
/**
* Constructor that takes in a class and sessionFactory for easy creation of DAO.
*
* @param persistentClass the class type you'd like to persist
* @param sessionFactory the pre-configured Hibernate SessionFactory
*/
public BaseDAOImpl(final Class<T> persistentClass, SessionFactory sessionFactory) {
this.persistentClass = persistentClass;
this.sessionFactory = sessionFactory;
this.hibernateTemplate = new HibernateTemplate(sessionFactory);
}
public HibernateTemplate getHibernateTemplate() {
return this.hibernateTemplate;
}
public SessionFactory getSessionFactory() {
return this.sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
this.hibernateTemplate = new HibernateTemplate(sessionFactory);
}
/**
* {@inheritDoc}
*/
public List<T> getAll() {
return hibernateTemplate.loadAll(this.persistentClass);
}
/**
* {@inheritDoc}
*/
public T get(PK id) {
T entity = (T) hibernateTemplate.get(this.persistentClass, id);
if (entity == null) {
throw new ObjectRetrievalFailureException(this.persistentClass, id);
}
return entity;
}
/**
* {@inheritDoc}
*/
public boolean exists(PK id) {
T entity = (T) hibernateTemplate.get(this.persistentClass, id);
return entity != null;
}
/**
* {@inheritDoc}
*/
public T save(T object) {
T obj = (T) hibernateTemplate.save(object);
hibernateTemplate.flush();
return obj;
}
/**
* {@inheritDoc}
*/
public void saveorUpdate(T object) {
hibernateTemplate.saveOrUpdate(object);
hibernateTemplate.flush();
}
/**
* {@inheritDoc}
*/
public void delete(PK id) {
hibernateTemplate.delete(this.get(id));
hibernateTemplate.flush();
}
public void update(T object) {
hibernateTemplate.update(object);
hibernateTemplate.flush();
}
public List<T> findByQuery(String queryString, Map<String, Object> queryParams) {
String[] params = new String[queryParams.size()];
Object[] values = new Object[queryParams.size()];
int index = 0;
for (String s : queryParams.keySet()) {
params[index] = s;
values[index++] = queryParams.get(s);
}
return hibernateTemplate.findByNamedParam(queryString, params, values);
}
}
IBASEDAO界面如下。
import java.io.Serializable;
import java.util.List;
import java.util.Map;
/**
* Generic DAO with common methods for CRUD operations.
*
* <p>Extend this interface if you want typesafe DAO's
* (no casting necessary)
*
* @param <T> a type variable
* @param <PK> the primary key for that type
*/
public interface IBaseDAO <T, PK extends Serializable> {
/**
* Generic method used to get all objects of a particular type. This
* is the same as lookup up all rows in a table.
* @return List of populated objects
*/
List<T> getAll();
/**
* Generic method to get an object based on class and identifier. An
* ObjectRetrievalFailureException Runtime Exception is thrown if
* nothing is found.
*
* @param id the identifier (primary key) of the object to get
* @return a populated object
* @see org.springframework.orm.ObjectRetrievalFailureException
*/
T get(PK id);
/**
* Checks for existence of an object of type T using the id arg.
* @param id the id of the entity
* @return - true if it exists, false if it doesn't
*/
boolean exists(PK id);
/**
* Generic method to save an object - handles both update and insert.
* @param object the object to save
* @return the persisted object
*/
T save(T object);
/**
* Generic method to save or Update an object - handles both update and insert.
* @param object the object to save
* @return the persisted object
*/
void saveorUpdate(T object);
/**
* Generic method to delete an object based on class and id
* @param id the identifier (primary key) of the object to remove
*/
void delete(PK id);
/**
* Generic method to get an object based on class and identifier. An
* ObjectRetrievalFailureException Runtime Exception is thrown if
* nothing is found.
*
* @param queryString, queryParams used to get
* @return a populated object
* @see org.springframework.orm.ObjectRetrievalFailureException
*/
List<T> findByQuery(String queryString, Map<String, Object> queryParams) ;
}
}
您的最终实施应该是这样的。
@Repository
public class FeedListDAOImpl extends BaseDAOImpl<YourModel.class, Integer> implements FeedListDAO{
private static final Logger LOG = Logger.getLogger(FeedListDAOImpl .class);
@Autowired
public FeedListDAOImpl (SessionFactory sessionFactory) {
super(YourModel.class);
super.setSessionFactory(sessionFactory);
}
请进行上述更改,主要是为了更好地抽象DAO类。希望这应该100%