英文:
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&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<Customer> getCustomers() {
// get the current hibernate session
Session currentSession = sessionFactory.getCurrentSession();
// create a query
Query<Customer> theQuery = 
currentSession.createQuery("from Customer", Customer.class);
// execute query and get result list
List<Customer> 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("/customer")
public class CustomerController {
// need to inject the customer dao
@Autowired(required = true)
private CustomerDAO customerDAO;
@RequestMapping("/list")
public String listcustomer(Model theModel) {
//get customer from dao
List<Customer> theCustomers  = customerDAO.getCustomers();
//add customer to model
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">
<!-- Add support for component scanning -->
<context:component-scan base-package="com.shadow.springdemo" />
<!-- Add support for conversion, formatting and validation support -->
<tx:annotation-driven/>
<!-- Define Spring MVC view resolver -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- Step 1: Define Database DataSource / connection pool -->
<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" /> 
<!-- these are connection pool properties for C3P0 -->
<property name="minPoolSize" value="5" />
<property name="maxPoolSize" value="20" />
<property name="maxIdleTime" value="30000" />
</bean>  
<!-- Step 2: Setup Hibernate session factory -->
<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>	  
<!-- Step 3: Setup Hibernate transaction manager -->
<bean id="myTransactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- Step 4: Enable configuration of transactional behavior based on annotations -->
<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>
答案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>
        <!-- 步骤 4:基于注解启用事务行为的配置 -->
<tx:annotation-driven transaction-manager="transactionManager" />
英文:
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>
        <!-- Step 4: Enable configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="transactionManager" />
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论