【问题标题】:BeanNotOfRequiredTypeException: Bean named X is expected to be of type X but was actually of type 'com.sun.proxy.$ProxyBeanNotOfRequiredTypeException:名为 X 的 Bean 应该属于 X 类型,但实际上属于“com.sun.proxy.$Proxy”类型
【发布时间】:2019-03-07 07:26:19
【问题描述】:

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

【问题讨论】:

    标签: java spring configuration


    【解决方案1】:

    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】:

      这里是 100% 修复:

      @EnableTransactionManagement(proxyTargetClass = true)
      

      【讨论】:

      【解决方案3】:

      我想你在某处激活了@ComponentScan,它会扫描你的@Service 注释XCalculationService 类。

      所以你应该XCalculationService 中删除 @Service

      删除

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

      来自ServiceConfiguration

      【讨论】:

      • 删除了@Service,同样的错误。我只有网络 @ComponentScan(basePackages = {"com.x.web"})
      猜你喜欢
      • 2021-03-21
      • 2014-12-09
      • 1970-01-01
      • 2013-01-10
      • 2012-01-13
      • 1970-01-01
      • 2016-12-31
      • 2021-04-02
      • 1970-01-01
      相关资源
      最近更新 更多