BeanNotOfRequiredTypeException:名为X的Bean应该是类型X,但实际上是类型'com.sun.proxy。$ Proxy

时间:2018-10-02 07:28:28

标签: java spring configuration

我有这样的类和Spring上下文。

如何解决此错误的Java配置,而不是xml?

我尝试了其他帖子中的一些解决方案,但没有成功。

@Service
@Transactional
public class XCalculationService implements VoidService<X> {
}

public interface VoidService<Input> {
}

@AllArgsConstructor
public class XService {
private XCalculationService calculationService;
}

@Configuration
public class ServiceConfiguration {
@Bean
public OrderService orderService(XCalculationService calculationService) {
    return new XService(calculationService);
}

@Bean
public XCalculationService calculationService() {
    return new XCalculationService ();
}
}

错误

BeanNotOfRequiredTypeException: Bean named 'calculationService' is expected to be of type 'com.x.XCalculationService' but was actually of type 'com.sun.proxy.$Proxy

3 个答案:

答案 0 :(得分:7)

这是100%修复:

@EnableTransactionManagement(proxyTargetClass = true)

答案 1 :(得分:2)

Java 代理正在处理接口,而不是具体的类。
使用 spring 文档进行推理:https://docs.spring.io/spring-framework/docs/3.0.0.M3/reference/html/ch08s06.html

If the target object to be proxied implements at least one interface then a JDK dynamic proxy will be used.

因此,当使用基于方面/代理的注解作为 @Transactional 时,Spring 将尝试代理具体的类,结果对象将是 VoidService 接口的实例,而不是 XCalculationService

因此您可以通过两种方式解决它:

  1. 使用@Arthur 解决方案并关闭 Java 的接口代理,转而使用 CGLib 来支持事务 @EnableTransactionManagement(proxyTargetClass = true)
  2. 不要在可注入字段中使用 XCalculationService 类型,而是仅使用其代理接口,即 VoidService

答案 2 :(得分:1)

我想您已经激活了某个地方的@ComponentScan,它会扫描您的@Service注释的XCalculationService类。

因此,您应该@Service中删除 XCalculationService

删除

@Bean
public XCalculationService calculationService() {
    return new XCalculationService ();
}

来自ServiceConfiguration