我有这样的类和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
答案 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
。
因此您可以通过两种方式解决它:
@EnableTransactionManagement(proxyTargetClass = true)
XCalculationService
类型,而是仅使用其代理接口,即 VoidService
。答案 2 :(得分:1)
我想您已经激活了某个地方的@ComponentScan
,它会扫描您的@Service
注释的XCalculationService
类。
因此,您应该从@Service
中删除 XCalculationService
或删除
@Bean
public XCalculationService calculationService() {
return new XCalculationService ();
}
来自ServiceConfiguration