自动装配时,Hibernate Template抛出错误

时间:2017-11-21 11:07:59

标签: java spring hibernate

目前我在控制器和HibernateTemplate之间遇到Autowire配置问题。

我无法追查错误。

  

我想做自动连接的Hibernate模板但是它给出了这个错误    需要手动提供hibernate模板的实现

下面给出了我的调度程序servlet,java控制器和错误

这个是我的调度程序servlet代码

           <beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:context = "http://www.springframework.org/schema/context"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans     
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/context 
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">

   <context:component-scan base-package = "com.chatbot.controllers" />



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


 <!-- Hibernate Configuration -->
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">

        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://192.168.0.46:3306/chatbotadmin" />
        <property name="username" value="root" />
        <property name="password" value="" />
    </bean>

    <!-- Hibernate template configuration -->

    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
        <property name="sessionFactory">
            <ref bean="sessionFactory"/>
        </property>
    </bean>
       <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">

        <property name="dataSource" ref="dataSource" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
        <property name="annotatedClasses">
            <list>
                 <value>com.chatbot.beans.QueryBean</value> 
                 <value>com.chatbot.beans.PatternBean</value>  
                 <value>com.chatbot.beans.OptionsBean</value>
                 <value>com.chatbot.beans.OperationBean</value> 
                 <value>com.chatbot.beans.ResponseBean</value> 

            </list>
        </property>

   </bean>
        <bean id="template" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">  
        <property name="sessionFactory" ref="sessionFactory"></property>  
        </bean>  


</beans>   

java控制器的代码

        public class AddOperations {

        @Autowired(required = true)
        HibernateTemplate t;

        @RequestMapping(value="/addoperations",method=RequestMethod.GET)
        public ModelAndView addItGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException, JSONException
        {
            JSONObject responseString = call(request,response);
            System.out.println(responseString);
            return new ModelAndView("AdminPanal","QueryRecords",responseString.toString());
        }



        @RequestMapping(value="/addoperations",method=RequestMethod.POST)
        public void addItPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException, JSONException
        {

            JSONObject responseString = call(request,response);
            System.out.println(responseString);
            response.getWriter().println(responseString);


        }

        @SuppressWarnings("unchecked")
        private JSONObject call(HttpServletRequest request, HttpServletResponse response) throws JSONException {

            // TODO Auto-generated method stub
            if(request.getParameter("data")!=null)
            {
                try
                {
                    System.out.println("Operation REQ==> "+ request.getParameter("data"));
                    JSONObject parsedRequest = Constant.getparsedRequest(request.getParameter("data"));

                    JSONArray arrayOfOperations = new JSONArray(parsedRequest.getString("Operations"));
                    String OPERATIONTITLE = new String();
                    String OPERATIONURL = new String();
                    String OPERATIONPARAMETERS = new String();
                    int LEVEL=0;
                    int QID=0;

                    if(parsedRequest.getString("QID").equals(""))
                    {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("status", "false");
                        jsonObject.put("message", "QID is blank..!!");
                        return jsonObject;
                    }
                    else
                    {
                        if(arrayOfOperations.length()>0)
                        {
                            QID = Integer.parseInt(parsedRequest.getString("QID"));

                            List<QueryBean> list = t.find("FROM QueryBean q where q.QID="+QID);

                            ArrayList<OperationBean> arrayList = new ArrayList<>();
                            if(list.size()!=0)
                            {
                                int count =0;
                                List<ResponseBean> queryResponse_check =  t.find("FROM ResponseBean r where r.queryBean = "+list.get(0));

                                if(queryResponse_check.size()>0)
                                {
                                    JSONObject jsonObject = new JSONObject();
                                    jsonObject.put("status", "false");
                                    jsonObject.put("message", "Response already exist..!!");
                                    return jsonObject;
                                }
                                else
                                {
                                    for(int i=0; i<arrayOfOperations.length(); i++)
                                    {
                                        JSONObject jsonObject = arrayOfOperations.getJSONObject(i);
                                        if(!jsonObject.getString("OPERATIONTITLE").equals(""))
                                        {
                                            OPERATIONTITLE = jsonObject.getString("OPERATIONTITLE");
                                            OPERATIONURL = jsonObject.getString("OPERATIONURL");
                                            OPERATIONPARAMETERS = jsonObject.getString("OPERATIONPARAMETERS");
                                            LEVEL = jsonObject.getInt("LEVEL");

                                            OperationBean OperationBean = new OperationBean(list.get(0), OPERATIONTITLE, OPERATIONURL, OPERATIONPARAMETERS,LEVEL, new Date(), new Date(), "");
                                            arrayList.add(OperationBean);
                                            for(int i1=0; i1<arrayList.size(); i1++)
                                                count = (int) t.save(arrayList.get(i1));
                                        }
                                    }
                                    if(count !=0)
                                    {
                                        JSONObject jsonObject = new JSONObject();
                                        jsonObject.put("status", "true");
                                        jsonObject.put("message", "Response added successfully..!!");
                                        return jsonObject;
                                    }

                                }

                            }

                        }
                        else
                        {

                        }
                    }
                }
                catch(JSONException je)
                {
                    je.printStackTrace();

                }
            }


                return null;


        }
    }

编译器给出的错误是

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'addOperations': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.springframework.orm.hibernate3.HibernateTemplate com.chatbot.controllers.AddOperations.t; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [org.springframework.orm.hibernate3.HibernateTemplate] 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: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.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:631)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:588)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:645)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:508)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:449)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:133)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1174)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1090)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:980)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4829)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5139)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1425)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1415)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
    at java.util.concurrent.AbstractExecutorService.submit(Unknown Source)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:941)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:839)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1425)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1415)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
    at java.util.concurrent.AbstractExecutorService.submit(Unknown Source)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:941)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:258)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:422)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:770)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:671)
    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:355)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:495)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.springframework.orm.hibernate3.HibernateTemplate com.chatbot.controllers.AddOperations.t; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [org.springframework.orm.hibernate3.HibernateTemplate] 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:506)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
    ... 50 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [org.springframework.orm.hibernate3.HibernateTemplate] 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:924)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:793)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:707)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:478)
    ... 52 more

Nov 21, 2017 4:03:52 PM org.apache.catalina.core.StandardContext loadOnStartup
SEVERE: Servlet [Demo_dispatcher] in web application [/DemoSpring] threw load() exception
org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [org.springframework.orm.hibernate3.HibernateTemplate] 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:924)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:793)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:707)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:478)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
    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.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:631)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:588)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:645)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:508)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:449)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:133)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1174)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1090)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:980)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4829)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5139)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1425)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1415)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
    at java.util.concurrent.AbstractExecutorService.submit(Unknown Source)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:941)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:839)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1425)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1415)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
    at java.util.concurrent.AbstractExecutorService.submit(Unknown Source)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:941)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:258)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:422)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:770)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:671)
    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:355)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:495)

3 个答案:

答案 0 :(得分:1)

要启用@Autowired,您必须注册'AutowiredAnnotationBeanPostProcessor',您可以通过两种方式执行此操作:

  1. 包括<context:annotation-config />
  2. 在Spring配置文件中添加Spring上下文。

    <beans
        //...
        xmlns:context="http://www.springframework.org/schema/context"
        ">
        //...
    
        <context:annotation-config />
        //...
    </beans>
    
    1. 包含AutowiredAnnotationBeanPostProcessor
    2. 直接在bean配置文件

      中包含'AutowiredAnnotationBeanPostProcessor'
      <beans xmlns="http://www.springframework.org/schema/beans"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          ..>
      
          <bean
          class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
              ...
      
          </beans>
      

答案 1 :(得分:0)

在您的应用程序上下文中没有类型为HibernateTempate的bean。

添加这些行

<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory"><ref bean="sessionFactory"/></property>
</bean>

在用户使用休眠模板之前,请先查看此answer

答案 2 :(得分:0)

您需要在弹簧配置中启用注释,尝试在弹簧配置中添加以下内容:

private static final ThreadLocal<ObjectMapper> objectMapperThreadLocal = new ThreadLocal<>();

public static ObjectMapper getObjectMapper() {
    ObjectMapper objectMapper = objectMapperThreadLocal.get();
    if (objectMapper == null) {
        objectMapper = new ObjectMapper();
        objectMapperThreadLocal.set(objectMapper);
    }
    return objectMapper;
}