在使用spring mvc和hibernate自动装配sessionfactory bean时遇到问题 [英] Having issues autowiring a sessionfactory bean with spring mvc and hibernate

查看:144
本文介绍了在使用spring mvc和hibernate自动装配sessionfactory bean时遇到问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在我的项目中实现自动布线,但似乎我的应用程序在运行它时没有在我的application-context.xml中看到我的SessionFactory定义。



我可能错过了一些非常明显的东西,尽管我已经尝试了几个解决方案,但是发现类似的问题没有成功。



我使用Spring MVC和Hibernate。

这是我的application-context.xml。

 <?xml version =1.0encoding =UTF-8?> 
< beans xmlns =http://www.springframework.org/schema/beans
xmlns:xsi =http://www.w3.org/2001/XMLSchema-instance
xmlns:aop =http://www.springframework.org/schema/aop
xmlns:tx =http://www.springframework.org/schema/tx
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.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/ schema / tx / spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop- 3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd\">

< context:annotation-config />
< context:component-scan base-package =arlua/>

< bean
class =org.springframework.web.servlet.view.InternalResourceViewResolver>
< property name =prefix>
< value> / pages /< / value>
< / property>
< property name =suffix>
<值> .jsp< /值>
< / property>
< / bean>

< bean id =serverDatasource
class =org.springframework.jdbc.datasource.DriverManagerDataSource>
< property name =driverClassName>
< value> oracle.jdbc.driver.OracleDriver< / value>
< / property>
< property name =url>
<值>网址< /值>
< / property>
< property name =username>
<值> $ {user}< /值>
< / property>
< property name =password>
<值> $ {pwd}< /值>
< / property>
< / bean>

< bean id =propertyPlaceholderConfigurer
class =org.springframework.beans.factory.config.PropertyPlaceholderConfigurer>
< property name =systemPropertiesModeNamevalue =SYSTEM_PROPERTIES_MODE_OVERRIDE/>
< property name =ignoreUnresolvablePlaceholdersvalue =true/>
< / bean>

< bean id =mySessionFactory
class =org.springframework.orm.hibernate3.annotation.LocalSessionFactoryBean>
< property name =mappingResources>
< list>
< value> mapping / user_info.hbm.xml< / value>
<值>映射/ login.hbm.xml< /值>
<值>映射/ linked_accounts.hbm.xml< /值>
< value> mapping / application_instance.hbm.xml< / value>
< / list>
< / property>
< property name =hibernateProperties>
<道具>
< prop key =hibernate.dialect> org.hibernate.dialect.MySQLDialect< / prop>
< prop key =hibernate.hbm2ddl.auto> update< / prop>
< /道具>
< / property>
< property name =dataSourceref =serverDatasource/>
< / bean>

< bean id =userInfoDaoImplclass =arlua.dao.impl.UserInfoDaoImpl>
< property name =sessionFactoryref =mySessionFactory/>
< / bean>

< bean id =loginDaoImplclass =arlua.dao.impl.LoginDaoImpl>
< property name =sessionFactoryref =mySessionFactory/>
< / bean>

< bean id =linkedAccountsDaoImplclass =arlua.dao.impl.LinkedAccountsDaoImpl>
< property name =sessionFactoryref =mySessionFactory/>
< / bean>
<! -
< bean id =applicationInstanceDaoImplclass =arlua.dao.impl.ApplicationInstanceDaoImpl>
< property name =sessionFactoryref =mySessionFactory/>
< / bean>
- >
<! - *************使用AOP进行交易管理**************** - >

< bean id =myTransactionManager
class =org.springframework.orm.hibernate3.HibernateTransactionManager>
< property name =sessionFactoryref =mySessionFactory/>
< / bean>

< aop:config>
< / aop:config>

< tx:advice id =txAdvicetransaction-manager =myTransactionManager>
< tx:attributes>
< tx:method name =saveEntity
propagation =REQUIRES_NEW
isolation =READ_COMMITTED
rollback-for =Exception/>
< tx:方法名称=updateEntity
propagation =REQUIRES_NEW
isolation =READ_COMMITTED
rollback-for =Exception/>
< tx:method name =getEntity
propagation =REQUIRES_NEW
isolation =READ_COMMITTED
rollback-for =Exception/>
< tx:method name =getAllEntities
propagation =REQUIRES_NEW
isolation =READ_COMMITTED
rollback-for =Exception/>
< / tx:属性>
< / tx:advice>

< / beans>

这里是我尝试自动装配的控制器类。

  package arlua.controller; 

导入arlua.dao.TableEntityFetchDao;
导入arlua.dao.impl.ApplicationInstanceDaoImpl;
导入arlua.service.SearchCriteria;
导入arlua.service.UserAction;
导入arlua.tables.ApplicationInstanceTable;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

@Controller
@SessionAttributes
public class SearchAppController {
@Autowired public ApplicationInstanceDaoImpl applicationInstanceDaoImpl;

私人字符串输入;
private ApplicationInstanceTable oldApp,newApp;
$ b @RequestMapping(value =/ search_app_instance,method = RequestMethod.POST)
public String mySearchMethod(@ModelAttribute(search_criteria)SearchCriteria search){
input = search .getInput();

if(input!= null)
input = input.toUpperCase();

返回redirect:search_app_instance;
}

@RequestMapping(/ search_app_instance)
public ModelAndView mySuccessMethod(){
ModelAndView model = new ModelAndView(search_app_instance);

//检查并确保应用程序存在
// ApplicationContext factory =
//新建ClassPathXmlApplicationContext(spring-namespace.xml);
// TableEntityFetchDao urd =(TableEntityFetchDao)factory.getBean(applicationInstanceDaoImpl);
尝试{
ApplicationInstanceTable app =
(ApplicationInstanceTable)applicationInstanceDaoImpl.getEntity(input);
oldApp = app;
//将应用程序数据加载到表中
model.addObject(app_id,app.getApplication_id());
model.addObject(name,app.getName());
model.addObject(default_exp_period,app.getDefault_expiration_period());
model.addObject(server,app.getServer());
model.addObject(description,app.getDescription());
model.addObject(active,app.getActive());
model.addObject(conn_string,app.getConn_string());
model.addObject(creation_date,app.getCreation_date()。getTime());
model.addObject(error,);
}
catch(Exception e){
if(input!= null)
{
model.addObject(error,Application could not be found。 );
input =;
}
}

返回模型;


$ b @RequestMapping(value =/ app_actions,method = RequestMethod.POST)
public String userActionsMethod(@ModelAttribute(user_action)UserAction action ,
@ModelAttribute(app_info)ApplicationInstanceTable app_info){
if(action.getAction()。equals(update_info))
{
newApp = app_info;
返回redirect:update_app_info;
}
返回redirect:search_app_instance;
}

@RequestMapping(/ update_app_info)
public ModelAndView updateInfoMethod(){
ModelAndView model = new ModelAndView(search_app_instance);

ApplicationContext factory =
ClassPathXmlApplicationContext(spring-namespace.xml);
TableEntityFetchDao urd =(TableEntityFetchDao)factory.getBean(applicationInstanceDaoImpl);
newApp.setApplication_id(oldApp.getApplication_id());
newApp.setCreation_date(oldApp.getCreation_date());
urd.updateEntity(newApp);

model.addObject(msg,Application'+ newApp.getApplication_id()+'modified successfully。);
返回模型;


$ b code $
$ ApplicationInstanceDaoImpl Class

  package arlua.dao.impl; 

导入arlua.dao.TableEntityFetchDao;
导入arlua.tables.ApplicationInstanceTable;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;

@Repository(applicationInstanceDaoImpl)
public class ApplicationInstanceDaoImpl extends TableEntityFetchDao {

public SessionFactory mySessionFactory;

@Resource(name =mySessionFactory)
public void setMySessionFactory(SessionFactory mySessionFactory){
this.mySessionFactory = mySessionFactory;


public void saveEntity(Object applicationInstance){
this.mySessionFactory.getCurrentSession()。save((ApplicationInstanceTable)applicationInstance);

$ b $ public ApplicationInstanceTable getEntity(Object application_id){
return(ApplicationInstanceTable)this.mySessionFactory.getCurrentSession()。
get(ApplicationInstanceTable.class,(String)application_id);
}

public void updateEntity(Object applicationInstance){
this.mySessionFactory.getCurrentSession()。update((ApplicationInstanceTable)applicationInstance);


public void deleteEntity(Object applicationInstance){
this.mySessionFactory.getCurrentSession()。delete((ApplicationInstanceTable)applicationInstance);
}

public List<?> getAllEntities(){
return this.mySessionFactory.getCurrentSession()。createQuery
(FROM application_instance)。list();




$ b TableEntityFetchDao class

  package arlua.dao; 

import java.util.List;

import org.hibernate.SessionFactory;

/ *
该类将用作所有其他数据访问实现类
的通用蓝图,用于在arlua表上执行基本的CRUD操作(即UserInfoDaoImpl )。
* /
public abstract class TableEntityFetchDao {

private SessionFactory sessionFactory;

public void setSessionFactory(SessionFactory sessionFactory){
this.sessionFactory = sessionFactory;
}

public abstract void saveEntity(final Object entity);

public abstract Object getEntity(final Object key);

public abstract void updateEntity(final Object entity);

public abstract void deleteEntity(final Object entity);

public abstract List<?> getAllEntities();
}

这里是我的堆栈跟踪的大部分。

  org.springframework.beans.factory.BeanCreationException:使用名称'org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping#0'创建bean时出错:初始化豆失败了;嵌套异常是org.springframework.beans.factory.BeanCreationException:创建名为'searchAppController'的bean时出错:注入自动装配依赖失败;嵌套异常是org.springframework.beans.factory.BeanCreationException:无法自动装入字段:public arlua.dao.impl.ApplicationInstanceDaoImpl arlua.controller.SearchAppController.applicationInstanceDaoImpl;嵌套异常是org.springframework.beans.factory.BeanCreationException:创建名为'applicationInstanceDaoImpl'的bean时出错:注入资源依赖性失败;嵌套异常是org.springframework.beans.factory.NoSuchBeanDefinitionException:没有名为'mySessionFactory'的bean在org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527)中定义

org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory $ 1.getObject(AbstractBeanFactory.java:291)
。在org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
在org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSin
在org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext。的java:425)$在org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276 b $ b)
。在org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197)在org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47)

在org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4206)
在org.apache.catalina.core.StandardContext.start(StandardContext.java:4705)
在org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
在org.apache .catalina.core.StandardHost.start(StandardHost.java:840)
at org。 apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
在org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463)
在org.apache.catalina。 core.StandardService.start(StandardService.java:525)
位于org.apache.catalina.core.StandardServer.start(StandardServer.java:754)
位于org.apache.catalina.startup.Catalina。启动(Catalina.java:595)
在sun.reflect.NativeMethodAccessorImpl.invoke0(本机方法)
在sun.reflect.NativeMethodAccessorImpl.invoke(来源不明)
在sun.reflect.DelegatingMethodAccessorImpl .invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
在org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
导致:org.springframework.beans.factory.BeanCreationException:创建名为'searchAppController'的bean时出错:注入自动布线依赖关系失败;嵌套异常是org.springframework.beans.factory.BeanCreationException:无法自动装入字段:public arlua.dao.impl.ApplicationInstanceDaoImpl arlua.controller.SearchAppController.applicationInstanceDaoImpl;嵌套异常是org.springframework.beans.factory.BeanCreationException:创建名为'applicationInstanceDaoImpl'的bean时出错:注入资源依赖性失败;嵌套异常是org.springframework.beans.factory.NoSuchBeanDefinitionException:在org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
中未定义名为'mySessionFactory'的bean
在org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1074)
在org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory $ 1.getObject(AbstractBeanFactory.java:291)
在org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
在org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
在org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
在org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1075)
在org.springframework.web.servlet.handler.AbstractUrlHandlerMapping.registerHandler(AbstractUrlHandlerMapping.java:383)
。在组织.springframework.web.servlet.handler.AbstractUrlHandlerMapping.registerHandler(AbstractUrlHandlerMapping.java:362)
在org.springframework.web.servlet.handler.AbstractDetectingUrlHandlerMapping.detectHandlers(AbstractDetectingUrlHandlerMapping.java:82)
。在组织.springframework.web.servlet.handler.AbstractDetectingUrlHandlerMapping.initApplicationContext(AbstractDetectingUrlHandlerMapping.java:58)
在org.springframework.context.support.ApplicationObjectSupport.initApplicationContext(应用程ationObjectSupport.java:119)
在org.springframework.web.context.support.WebApplicationObjectSupport.initApplicationContext(WebApplicationObjectSupport.java:72)
在org.springframework.context.support.ApplicationObjectSupport.setApplicationContext(ApplicationObjectSupport。的java:在org.springframework.context.support.ApplicationContextAwareProcessor.invokeAwareInterfaces(ApplicationContextAwareProcessor.java:106)
。在org.springframework.context.support.ApplicationContextAwareProcessor.postProcessBeforeInitialization 73)
(ApplicationContextAwareProcessor.java:85)在org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:394)

在org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1413)
at org.springframework.beans.factory.support.AbstractAutowireCap ableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
... 26多个
引起的:org.springframework.beans.factory.BeanCreationException:无法自动装配领域:公共arlua.dao.impl.ApplicationInstanceDaoImpl arlua .controller.SearchAppController.applicationInstanceDaoImpl;嵌套异常是org.springframework.beans.factory.BeanCreationException:创建名为'applicationInstanceDaoImpl'的bean时出错:注入资源依赖性失败;嵌套异常是org.springframework.beans.factory.NoSuchBeanDefinitionException:没有名为'mySessionFactory'的bean在org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor $ AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:502)中定义

at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:84)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:282)
... 46 more
导致:org.springframework.beans.factory.BeanCreationException:创建名为'applicationInstanceDaoImpl'的bean时出错:注入资源依赖性失败;嵌套异常是org.springframework.beans.factory.NoSuchBeanDefinitionException:没有名为'mySessionFactory'的bean在org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:300)中定义
.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1074)
在org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
。在组织.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory $ 1.getObject(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.sprin gframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
在org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
。在组织。 springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:844)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:786)
at org。 springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:703)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor $ AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:474)
。 .. 48 more
导致:org.springframework.beans.factory.NoSuchBeanDefinitionException:没有名为'mySessionFactory'的Bean在org.springframework.beans.factory.support.Defaul中被定义为
tListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:527)
位于org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1083)
位于org.springframework.beans.factory.support。 AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:274)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor。 autowireResource(CommonAnnotationBeanPostProcessor.java:435)
在org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:409)
在org.springframework.context.annotation.CommonAnnotationBeanPostProcessor $ ResourceElement.getResourceToInject( CommonAnnotationBeanPostProcessor.java:541)$ or $
在org.springframework.beans.factory.annotation.InjectionMetadata $ InjectedElement.inject(InjectionMetad ata.java:156)
在org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:84)
在org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor会。 java:297)
... 59 more

编辑:我最终通过自动装配到接口TableEntityFetchDao中而不是实现它的类ApplicationInstanceDaoImpl来解决问题。

因此, / p>

  @Autowired public ApplicationInstanceDaoImpl applicationInstanceDaoImpl; 

成为这个

  @Autowired public TableEntityFetchDao applicationInstanceDao; 

这似乎解决了我的问题。



  @Resource(name =mySessionFactory)
public void setMySessionFactory(SessionFactory mySessionFactory){
this.mySessionFactory = mySessionFactory;

使用:

  @Autowired 
private SessionFactory mySessionFactory;

编辑

<



不知道为什么method不起作用,但我猜测父母 TableEntityFetchDao 类具有会话工厂的setter,然后 ApplicationInstanceDaoImpl - 子类重写它,并由于某种原因弹出不喜欢它,如果 TableEntityFetchDao @Resource @Autowired 具有相同的用途,所以set c将被注入,区别在于 @Resource 允许指定注入的bean的名称, @Autowire 允许您标记bean不需要。



获得 @Resource 我会尝试从父类中移除setter方法。无论哪种方式,它没有意义,因为它没有被使用。还有sessionFactory字段。这也可以被删除。然后,类只包含抽象方法,可以作为一个接口。另外,我会用 @Service 注释来注释 TableEntityFetchDao ,以便更好地理解它是一个服务层类。


I am trying to implement auto-wiring into my project, but it seems that my application isn't seeing my SessionFactory definition in my application-context.xml when I am running it.

I'm probably missing something really obvious, though I've tried several solutions from posts having similar issues with no success.

I am using Spring MVC and Hibernate.

Here is my 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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">

    <context:annotation-config />
    <context:component-scan base-package="arlua" />

    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/pages/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>

    <bean id="serverDatasource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName">
            <value>oracle.jdbc.driver.OracleDriver</value>
        </property>
        <property name="url">
            <value>url</value>
        </property>
        <property name="username">
            <value>${user}</value>
        </property>
        <property name="password">
            <value>${pwd}</value>
        </property>
    </bean>

    <bean id="propertyPlaceholderConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
        <property name="ignoreUnresolvablePlaceholders" value="true"/>
    </bean>

    <bean id="mySessionFactory"
        class="org.springframework.orm.hibernate3.annotation.LocalSessionFactoryBean">
        <property name="mappingResources">
            <list>
                <value>mapping/user_info.hbm.xml</value>
                <value>mapping/login.hbm.xml</value>
                <value>mapping/linked_accounts.hbm.xml</value>
                <value>mapping/application_instance.hbm.xml</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
        <property name="dataSource" ref="serverDatasource"/>
    </bean>

    <bean id = "userInfoDaoImpl" class="arlua.dao.impl.UserInfoDaoImpl">
        <property name="sessionFactory" ref="mySessionFactory"/>
    </bean>

    <bean id = "loginDaoImpl" class="arlua.dao.impl.LoginDaoImpl">
        <property name="sessionFactory" ref="mySessionFactory"/>
    </bean>

    <bean id = "linkedAccountsDaoImpl" class="arlua.dao.impl.LinkedAccountsDaoImpl">
        <property name="sessionFactory" ref="mySessionFactory"/>
    </bean>
    <!--
    <bean id = "applicationInstanceDaoImpl" class="arlua.dao.impl.ApplicationInstanceDaoImpl">
        <property name="sessionFactory" ref="mySessionFactory"/>
    </bean>
     -->
    <!--  *************  TRANSACTION MANAGEMENT USING AOP **************** -->

    <bean id="myTransactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="mySessionFactory"/>    
    </bean>

    <aop:config>
        <aop:pointcut id="allMethods" expression="execution(* arlua.dao.TableEntityFetchDao.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="allMethods"/>
    </aop:config>

    <tx:advice id="txAdvice" transaction-manager="myTransactionManager">
        <tx:attributes>
            <tx:method name="saveEntity"
                propagation = "REQUIRES_NEW"
                isolation = "READ_COMMITTED"
                rollback-for = "Exception"/>
            <tx:method name="updateEntity"
                propagation = "REQUIRES_NEW"
                isolation = "READ_COMMITTED"
                rollback-for = "Exception"/>
            <tx:method name="getEntity"
                propagation = "REQUIRES_NEW"
                isolation = "READ_COMMITTED"
                rollback-for = "Exception"/>
            <tx:method name="getAllEntities"
                propagation = "REQUIRES_NEW"
                isolation = "READ_COMMITTED"
                rollback-for = "Exception"/>
        </tx:attributes>
    </tx:advice>

</beans>

Here is the controller class where I am trying to autowire.

package arlua.controller;

import arlua.dao.TableEntityFetchDao;
import arlua.dao.impl.ApplicationInstanceDaoImpl;
import arlua.service.SearchCriteria;
import arlua.service.UserAction;
import arlua.tables.ApplicationInstanceTable;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

@Controller
@SessionAttributes
public class SearchAppController{
    @Autowired public ApplicationInstanceDaoImpl applicationInstanceDaoImpl;

    private String input;
    private ApplicationInstanceTable oldApp, newApp;

    @RequestMapping(value = "/search_app_instance", method = RequestMethod.POST)
    public String mySearchMethod(@ModelAttribute("search_criteria") SearchCriteria search){
        input = search.getInput();

        if(input != null)
            input = input.toUpperCase();

        return "redirect:search_app_instance";
    }

    @RequestMapping("/search_app_instance")
    public ModelAndView mySuccessMethod(){
        ModelAndView model = new ModelAndView("search_app_instance");

            //Check and Make sure that the app exists
            //ApplicationContext factory = 
            //  new ClassPathXmlApplicationContext("spring-namespace.xml");
            //TableEntityFetchDao urd = (TableEntityFetchDao)factory.getBean("applicationInstanceDaoImpl");
            try{
                ApplicationInstanceTable app = 
                    (ApplicationInstanceTable) applicationInstanceDaoImpl.getEntity(input);
                oldApp = app;
                //Load app data into table
                model.addObject("app_id", app.getApplication_id());
                model.addObject("name", app.getName());
                model.addObject("default_exp_period", app.getDefault_expiration_period());
                model.addObject("server", app.getServer());
                model.addObject("description", app.getDescription());
                model.addObject("active", app.getActive());
                model.addObject("conn_string", app.getConn_string());
                model.addObject("creation_date", app.getCreation_date().getTime());
                model.addObject("error", "");
            }
            catch(Exception e){
                if(input != null)
                {
                    model.addObject("error", "Application could not be found.");
                    input = "";
                }
            }

        return model;
    }


    @RequestMapping(value = "/app_actions", method = RequestMethod.POST)
    public String userActionsMethod(@ModelAttribute("user_action") UserAction action, 
            @ModelAttribute("app_info") ApplicationInstanceTable app_info){
        if(action.getAction().equals("update_info"))
        {
            newApp = app_info;
            return "redirect:update_app_info";
        }
        return "redirect:search_app_instance";
    }

    @RequestMapping("/update_app_info")
    public ModelAndView updateInfoMethod(){
        ModelAndView model = new ModelAndView("search_app_instance");

            ApplicationContext factory = 
                new ClassPathXmlApplicationContext("spring-namespace.xml");
            TableEntityFetchDao urd = (TableEntityFetchDao)factory.getBean("applicationInstanceDaoImpl");
            newApp.setApplication_id(oldApp.getApplication_id());
            newApp.setCreation_date(oldApp.getCreation_date());
            urd.updateEntity(newApp);

        model.addObject("msg", "Application '" + newApp.getApplication_id() + "' modified successfully.");
        return model;
    }

}

ApplicationInstanceDaoImpl Class

package arlua.dao.impl;

import arlua.dao.TableEntityFetchDao;
import arlua.tables.ApplicationInstanceTable;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;

@Repository("applicationInstanceDaoImpl")
public class ApplicationInstanceDaoImpl extends TableEntityFetchDao{

    public SessionFactory mySessionFactory;

    @Resource(name = "mySessionFactory")
    public void setMySessionFactory(SessionFactory mySessionFactory){
        this.mySessionFactory = mySessionFactory;
    }

    public void saveEntity(Object applicationInstance) {
        this.mySessionFactory.getCurrentSession().save((ApplicationInstanceTable)applicationInstance);
    }

    public ApplicationInstanceTable getEntity(Object application_id) {
        return (ApplicationInstanceTable)this.mySessionFactory.getCurrentSession().
            get(ApplicationInstanceTable.class, (String)application_id);
    }

    public void updateEntity(Object applicationInstance) {
        this.mySessionFactory.getCurrentSession().update((ApplicationInstanceTable)applicationInstance);
    }

    public void deleteEntity(Object applicationInstance) {
        this.mySessionFactory.getCurrentSession().delete((ApplicationInstanceTable)applicationInstance);
    }

    public List<?> getAllEntities() {
        return this.mySessionFactory.getCurrentSession().createQuery
            ("FROM application_instance").list();
    }
}

TableEntityFetchDao class

package arlua.dao;

import java.util.List;

import org.hibernate.SessionFactory;

/*
This class will serve as a generic blueprint for all of the other data access implementation classes
that are used to perform basic CRUD operations on the arlua tables (ie UserInfoDaoImpl).
 */
public abstract class TableEntityFetchDao {

    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory){
        this.sessionFactory = sessionFactory;
    }

    public abstract void saveEntity(final Object entity);

    public abstract Object getEntity(final Object key);

    public abstract void updateEntity(final Object entity);

    public abstract void deleteEntity(final Object entity);

    public abstract List<?> getAllEntities();
}

Here is most of my stack trace.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping#0': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'searchAppController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public arlua.dao.impl.ApplicationInstanceDaoImpl arlua.controller.SearchAppController.applicationInstanceDaoImpl; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'applicationInstanceDaoImpl': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'mySessionFactory' is defined
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
    at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4206)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4705)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
    at org.apache.catalina.core.StandardHost.start(StandardHost.java:840)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
    at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463)
    at org.apache.catalina.core.StandardService.start(StandardService.java:525)
    at org.apache.catalina.core.StandardServer.start(StandardServer.java:754)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:595)
    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.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'searchAppController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public arlua.dao.impl.ApplicationInstanceDaoImpl arlua.controller.SearchAppController.applicationInstanceDaoImpl; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'applicationInstanceDaoImpl': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'mySessionFactory' is defined
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1074)
    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:291)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1075)
    at org.springframework.web.servlet.handler.AbstractUrlHandlerMapping.registerHandler(AbstractUrlHandlerMapping.java:383)
    at org.springframework.web.servlet.handler.AbstractUrlHandlerMapping.registerHandler(AbstractUrlHandlerMapping.java:362)
    at org.springframework.web.servlet.handler.AbstractDetectingUrlHandlerMapping.detectHandlers(AbstractDetectingUrlHandlerMapping.java:82)
    at org.springframework.web.servlet.handler.AbstractDetectingUrlHandlerMapping.initApplicationContext(AbstractDetectingUrlHandlerMapping.java:58)
    at org.springframework.context.support.ApplicationObjectSupport.initApplicationContext(ApplicationObjectSupport.java:119)
    at org.springframework.web.context.support.WebApplicationObjectSupport.initApplicationContext(WebApplicationObjectSupport.java:72)
    at org.springframework.context.support.ApplicationObjectSupport.setApplicationContext(ApplicationObjectSupport.java:73)
    at org.springframework.context.support.ApplicationContextAwareProcessor.invokeAwareInterfaces(ApplicationContextAwareProcessor.java:106)
    at org.springframework.context.support.ApplicationContextAwareProcessor.postProcessBeforeInitialization(ApplicationContextAwareProcessor.java:85)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:394)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1413)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
    ... 26 more
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: public arlua.dao.impl.ApplicationInstanceDaoImpl arlua.controller.SearchAppController.applicationInstanceDaoImpl; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'applicationInstanceDaoImpl': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'mySessionFactory' is defined
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:502)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:84)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:282)
    ... 46 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'applicationInstanceDaoImpl': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'mySessionFactory' is defined
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:300)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1074)
    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:291)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:844)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:786)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:703)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:474)
    ... 48 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'mySessionFactory' is defined
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:527)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1083)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:274)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:435)
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:409)
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:541)
    at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:156)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:84)
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:297)
    ... 59 more

Edit: I ended up fixing my problem by autowiring into the interface TableEntityFetchDao rather than the class that was implementing it, ApplicationInstanceDaoImpl.

So, this

@Autowired public ApplicationInstanceDaoImpl applicationInstanceDaoImpl;

Became this

@Autowired public TableEntityFetchDao applicationInstanceDao;

And that seemed to fix my problem.

解决方案

Instead of:

@Resource(name = "mySessionFactory")
public void setMySessionFactory(SessionFactory mySessionFactory){
    this.mySessionFactory = mySessionFactory;
}

Use:

@Autowired
private SessionFactory mySessionFactory;

EDIT

As of the bellow comment:

Not sure why method is not working but my guess is that the parent TableEntityFetchDao class has the setter of session factory, then ApplicationInstanceDaoImpl - child class overrides it and spring for some reason does not like it, if TableEntityFetchDao would be an interface, setter would be injected, as @Resource serves the same purpose as @Autowired difference is that @Resource allows to specify the name of the bean which is injected, and @Autowire allows you mark the bean as not required.

To get @Resource working I would try to remove setter method from the parent class. Either way it makes no sense of having it there as it is not used. Also sessionFactory field. This can be removed as well. Then class contains only abstract methods and can be made an interface. Also I would annotate TableEntityFetchDao with @Service annotation for better understanding that it is a service-layer class.

这篇关于在使用spring mvc和hibernate自动装配sessionfactory bean时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆