提问者:小点点

BeanNotOf必需的类型异常:名为X的Bean应该是X类型,但实际上是'com. sun.proxy类型。$代理


我有这样的类和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个答案

匿名用户

这是100%修复:

@EnableTransactionManagement(proxyTargetClass = true)

匿名用户

Java代理处理的是接口,而不是具体的类。
Spring留档推理:https://docs.spring.io/spring-framework/docs/3.0.0.M3/reference/html/ch08s06.html

如果要代理的目标对象至少实现了一个接口,那么将使用JDK动态代理。

因此,当使用基于方面/代理的注释作为@Transactional时,Spring将尝试代理具体类,并且结果对象将是VoidService接口的实例,而不是X计算服务

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

  1. 使用@Arthur解决方案并关闭Java的接口代理以支持CGLib以获得事务支持@EnableTransactionManagement(proxyTargetClass=true)
  2. 不要在可注入字段中使用X计算服务类型,而只使用其代理接口,即VoidService

匿名用户

我假设您在某处激活了@ComponentScan,它会扫描您的@Service注释的XComponentScan类。

因此,您应该从X79ationService中删除@Service

或删除

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

ServiceConfiguration