我有这样的类和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
这是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计算服务
。
因此,您可以通过两种方式解决它:
@EnableTransactionManagement(proxyTargetClass=true)
X计算服务
类型,而只使用其代理接口,即VoidService
。
我假设您在某处激活了@ComponentScan
,它会扫描您的@Service
注释的XComponentScan
类。
因此,您应该从X79ationService
中删除@Service
或删除
@Bean
public XCalculationService calculationService() {
return new XCalculationService ();
}
从ServiceConfiguration