当前位置: 首页 > 知识库问答 >
问题:

使用@Transactional注释方法会导致“未定义类型的唯一bean:预期单个bean但发现0”

单喜
2023-03-14

在实现类中用@Transactional注释方法会引发此异常

// Interface
public interface JobManager {

    public void process(CommandLine parameters);
}

// Implementing class
public class UserJobManager implements JobManager{

    @Transactional
    @Override
    public void process(CommandLine line) {
        // Stuff here
    }
}

Spring配置:

<?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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context.xsd">

    <bean id="benchmarkManager" class="com.test.userjobmanager.UserJobManager"/>

    <tx:annotation-driven transaction-manager="transactionManager" order="10"/>

    <bean id="transactionManager" 
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

         <property name="dataSource" ref="readDataSource"/>
    </bean>

    <!-- other beans here -->
</beans>

当我访问bean时,就像:

JobManager jobManager = ac.getBean(UserJobManager.class);

我有以下线索:

线程"main"org.springframework.beans.factory.NoSuchBean定义异常:未定义[com.test.userjobmanager.UserJobManager]类型的唯一bean:预期单个bean但发现0:org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:269)org.springframework.context.support.AbstractApplication Context.getBean(AbstractApplication Context.java:1083)

如果我删除@Transactional,它可以正常工作。我不确定这里有什么问题。

共有1个答案

吕英豪
2023-03-14

也许您正在使用创建合成类的代理技术。也就是说,您的事务性bean的真实类可能不再是UserJobManager。我建议改为按名称访问bean:

JobManager jobManager = ac.getBean("benchmarkManager", JobManager.class)
 类似资料: