No bean named ‘transactionManager’ available

huangapple go评论77阅读模式
英文:

No bean named 'transactionManager' available:

问题

请求处理失败嵌套异常为 org.springframework.beans.factory.NoSuchBeanDefinitionException无法找到名为 'transactionManager' 的 bean无法找到匹配的 TransactionManager bean既不匹配限定符也不匹配 bean 名称

CustomerDAOImpl.java

package com.shadow.springdemo.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.shadow.springdemo.entity.Customer;

@Repository
public class CustomerDAOImpl implements CustomerDAO {

    // 需要注入会话工厂
    @Autowired
    private SessionFactory sessionFactory;

    @Override
    @Transactional
    public List<Customer> getCustomers() {

        // 获取当前的 Hibernate 会话
        Session currentSession = sessionFactory.getCurrentSession();

        // 创建一个查询
        Query<Customer> theQuery =
            currentSession.createQuery("from Customer", Customer.class);

        // 执行查询并获取结果列表
        List<Customer> customers = theQuery.getResultList();

        // 返回结果
        return customers;
    }
}


CustomerController

package com.shadow.springdemo.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.shadow.springdemo.dao.CustomerDAO;
import com.shadow.springdemo.entity.Customer;

@Controller
@RequestMapping("/customer")
public class CustomerController {

    // 需要注入客户 DAO
    @Autowired(required = true)
    private CustomerDAO customerDAO;

    @RequestMapping("/list")
    public String listcustomer(Model theModel) {

        // 从 DAO 获取客户
        List<Customer> theCustomers = customerDAO.getCustomers();

        // 将客户添加到模型
        theModel.addAttribute("customers", theCustomers);

        return "list-customer";
    }
}


CustomerDAO

package com.shadow.springdemo.dao;

import java.util.List;

import com.shadow.springdemo.entity.Customer;

public interface CustomerDAO {

    public List<Customer> getCustomers();
}


spring-mvc-crud-demo-servlet.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:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
      http://www.springframework.org/schema/aop
      http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context-2.5.xsd
      http://www.springframework.org/schema/tx
      http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

    <!-- 添加对组件扫描的支持 -->
    <context:component-scan base-package="com.shadow.springdemo" />

    <!-- 添加对转换格式化和验证的支持 -->
    <tx:annotation-driven />

    <!-- 定义 Spring MVC 视图解析器 -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <!-- 步骤 1定义数据库数据源 / 连接池 -->
    <bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
        destroy-method="close">
        <property name="driverClass" value="com.mysql.cj.jdbc.Driver" />
        <property name="jdbcUrl"
            value="jdbc:mysql://localhost:3306/web_customer_tracker?useSSL=false&amp;serverTimezone=UTC" />
        <property name="user" value="student" />
        <property name="password" value="student" />

        <!-- 这些是 C3P0 的连接池属性 -->
        <property name="minPoolSize" value="5" />
        <property name="maxPoolSize" value="20" />
        <property name="maxIdleTime" value="30000" />
    </bean>

    <!-- 步骤 2设置 Hibernate 会话工厂 -->
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="myDataSource" />
        <property name="packagesToScan" value="com.shadow.springdemo.entity" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>

    <!-- 步骤 3设置 Hibernate 事务管理器 -->
    <bean id="myTransactionManager"
        class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <!-- 步骤 4基于注解启用事务行为的配置 -->
    <tx:annotation-driven transaction-manager="myTransactionManager" />

</beans>


Web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    id="WebApp_ID" version="3.1">
  <display-name>spring-mvc-crud-demo</display-name>

  <absolute-ordering />

  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>

  <servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/spring-mvc-crud-demo-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>
英文:

Request processing failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'transactionManager' available: No matching TransactionManager bean found for qualifier 'transactionManager' - neither qualifier match nor bean name match!

CustomerDAOImpl.java

package com.shadow.springdemo.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.shadow.springdemo.entity.Customer;
@Repository
public class CustomerDAOImpl implements CustomerDAO {
// need to inject the session factory
@Autowired
private SessionFactory sessionFactory;
@Override
@Transactional
public List&lt;Customer&gt; getCustomers() {
// get the current hibernate session
Session currentSession = sessionFactory.getCurrentSession();
// create a query
Query&lt;Customer&gt; theQuery = 
currentSession.createQuery(&quot;from Customer&quot;, Customer.class);
// execute query and get result list
List&lt;Customer&gt; customers = theQuery.getResultList();
// return the results		
return customers;
}
}

CustomerController

		package com.shadow.springdemo.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.shadow.springdemo.dao.CustomerDAO;
import com.shadow.springdemo.entity.Customer;
@Controller
@RequestMapping(&quot;/customer&quot;)
public class CustomerController {
// need to inject the customer dao
@Autowired(required = true)
private CustomerDAO customerDAO;
@RequestMapping(&quot;/list&quot;)
public String listcustomer(Model theModel) {
//get customer from dao
List&lt;Customer&gt; theCustomers  = customerDAO.getCustomers();
//add customer to model
theModel.addAttribute(&quot;customers&quot;, theCustomers);
return &quot;list-customer&quot;;
}
}

CustomerDAO

		package com.shadow.springdemo.dao;
import java.util.List;
import com.shadow.springdemo.entity.Customer;
public interface CustomerDAO {
public List&lt;Customer&gt; getCustomers();
}

spring-mvc-crud-demo-servlet.xml

			&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; 
xmlns:context=&quot;http://www.springframework.org/schema/context&quot;
xmlns:tx=&quot;http://www.springframework.org/schema/tx&quot;
xmlns:mvc=&quot;http://www.springframework.org/schema/mvc&quot;
xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
&lt;!-- Add support for component scanning --&gt;
&lt;context:component-scan base-package=&quot;com.shadow.springdemo&quot; /&gt;
&lt;!-- Add support for conversion, formatting and validation support --&gt;
&lt;tx:annotation-driven/&gt;
&lt;!-- Define Spring MVC view resolver --&gt;
&lt;bean
class=&quot;org.springframework.web.servlet.view.InternalResourceViewResolver&quot;&gt;
&lt;property name=&quot;prefix&quot; value=&quot;/WEB-INF/view/&quot; /&gt;
&lt;property name=&quot;suffix&quot; value=&quot;.jsp&quot; /&gt;
&lt;/bean&gt;
&lt;!-- Step 1: Define Database DataSource / connection pool --&gt;
&lt;bean id=&quot;myDataSource&quot; class=&quot;com.mchange.v2.c3p0.ComboPooledDataSource&quot;
destroy-method=&quot;close&quot;&gt;
&lt;property name=&quot;driverClass&quot; value=&quot;com.mysql.cj.jdbc.Driver&quot; /&gt;
&lt;property name=&quot;jdbcUrl&quot; value=&quot;jdbc:mysql://localhost:3306/web_customer_tracker?useSSL=false&amp;amp;serverTimezone=UTC&quot; /&gt;
&lt;property name=&quot;user&quot; value=&quot;student&quot; /&gt;
&lt;property name=&quot;password&quot; value=&quot;student&quot; /&gt; 
&lt;!-- these are connection pool properties for C3P0 --&gt;
&lt;property name=&quot;minPoolSize&quot; value=&quot;5&quot; /&gt;
&lt;property name=&quot;maxPoolSize&quot; value=&quot;20&quot; /&gt;
&lt;property name=&quot;maxIdleTime&quot; value=&quot;30000&quot; /&gt;
&lt;/bean&gt;  
&lt;!-- Step 2: Setup Hibernate session factory --&gt;
&lt;bean id=&quot;sessionFactory&quot;
class=&quot;org.springframework.orm.hibernate5.LocalSessionFactoryBean&quot;&gt;
&lt;property name=&quot;dataSource&quot; ref=&quot;myDataSource&quot; /&gt;
&lt;property name=&quot;packagesToScan&quot; value=&quot;com.shadow.springdemo.entity&quot; /&gt;
&lt;property name=&quot;hibernateProperties&quot;&gt;
&lt;props&gt;
&lt;prop key=&quot;hibernate.dialect&quot;&gt;org.hibernate.dialect.MySQLDialect&lt;/prop&gt;
&lt;prop key=&quot;hibernate.show_sql&quot;&gt;true&lt;/prop&gt;
&lt;/props&gt;
&lt;/property&gt;
&lt;/bean&gt;	  
&lt;!-- Step 3: Setup Hibernate transaction manager --&gt;
&lt;bean id=&quot;myTransactionManager&quot;
class=&quot;org.springframework.orm.hibernate5.HibernateTransactionManager&quot;&gt;
&lt;property name=&quot;sessionFactory&quot; ref=&quot;sessionFactory&quot;/&gt;
&lt;/bean&gt;
&lt;!-- Step 4: Enable configuration of transactional behavior based on annotations --&gt;
&lt;tx:annotation-driven transaction-manager=&quot;myTransactionManager&quot; /&gt;
&lt;/beans&gt;

Web.xml

			&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;web-app xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xmlns=&quot;http://xmlns.jcp.org/xml/ns/javaee&quot; xsi:schemaLocation=&quot;http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd&quot; id=&quot;WebApp_ID&quot; version=&quot;3.1&quot;&gt;
&lt;display-name&gt;spring-mvc-crud-demo&lt;/display-name&gt;
&lt;absolute-ordering /&gt;
&lt;welcome-file-list&gt;
&lt;welcome-file&gt;index.jsp&lt;/welcome-file&gt;
&lt;welcome-file&gt;index.html&lt;/welcome-file&gt;
&lt;/welcome-file-list&gt;
&lt;servlet&gt;
&lt;servlet-name&gt;dispatcher&lt;/servlet-name&gt;
&lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt;
&lt;init-param&gt;
&lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
&lt;param-value&gt;/WEB-INF/spring-mvc-crud-demo-servlet.xml&lt;/param-value&gt;
&lt;/init-param&gt;
&lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
&lt;/servlet&gt;
&lt;servlet-mapping&gt;
&lt;servlet-name&gt;dispatcher&lt;/servlet-name&gt;
&lt;url-pattern&gt;/&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
&lt;/web-app&gt;

答案1

得分: 1

提及 Spring 文档

> 两个示例之间的一个小差异在于 TransactionManager bean 的命名:在 @Bean 的情况下,名称为 "txManager"(根据方法的名称);在 XML 的情况下,名称为 "transactionManager"。<tx:annotation-driven/> 被硬编码为寻找一个名为 "transactionManager" 的 bean

因此在你的 XML 中,将 bean 名称从 myTransaction 重命名为 transactionManager

<!-- 步骤 3:设置 Hibernate 事务管理器 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>

        &lt;!-- 步骤 4:基于注解启用事务行为的配置 --&gt;
&lt;tx:annotation-driven transaction-manager=&quot;transactionManager&quot; /&gt;
英文:

referring Spring document

> A minor difference between the two examples lies in the naming of the
> TransactionManager bean: In the @Bean case, the name is "txManager"
> (per the name of the method); in the XML case, the name is
> "transactionManager". The <tx:annotation-driven/> is hard-wired to
> look for a bean named "transactionManager"

hence in ur xml rename the bean myTransaction to transactionManager

<!-- Step 3: Setup Hibernate transaction manager -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>

        &lt;!-- Step 4: Enable configuration of transactional behavior based on annotations --&gt;
&lt;tx:annotation-driven transaction-manager=&quot;transactionManager&quot; /&gt;

huangapple
  • 本文由 发表于 2020年9月27日 06:11:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/64082955.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定