gpt4 book ai didi

java - 为什么 @Validated + @Component + Implement 会在 Spring Boot 中导致类型误导性错误?

转载 作者:太空宇宙 更新时间:2023-11-04 09:56:31 25 4
gpt4 key购买 nike

这里是代码示例列表:

基础

@Validated
@Component
public class MyImpl1 {}

@Validated
@Component
public class MyImpl2 {}

@Service
public MySelector {
private final MyImpl1 myImpl1;
private final MyImpl2 myImpl2;

@Autowired
public MySelector(MyImpl1 myImpl1, MyImpl2 myImpl2) {
this.myImpl1 = myImpl1;
this.myImpl2 = myImpl2;
}

public Object select (Long id) {
switch (id) {
case 1:
return myImpl1;
case 2:
return myImpl1;
}
}
}

有效:bean 被注入(inject),这里没有问题。这里重要的注意事项是 MyImpl beans 是代理,这是否 Autowiring 的问题。

但是当我像这样添加implements时,事情会变得不同:

实现

@Validated
@Component
public class MyImpl1 implements MyInterface{}

@Validated
@Component
public class MyImpl2 implements MyInterface{}

public interface MyInterface {}

@Service
public MySelector {
private final MyImpl1 myImpl1;
private final MyImpl2 myImpl2;

@Autowired
public MySelector(MyImpl1 myImpl1, MyImpl2 myImpl2) {
this.myImpl1 = myImpl1;
this.myImpl2 = myImpl2;
}

public Object select (Long id) {
switch (id) {
case 1:
return myImpl1;
case 2:
return myImpl2;
}
}
}

我得到了:

Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'myImpl1' is expected to be of type 'MyImpl1' but was actually of type 'com.sun.proxy.$Proxy108'

如果我删除@Validated前夕让我们重新开始工作。

据我了解,spring使用代理,最好使用接口(interface)。但我不明白为什么我在这里遇到问题?如果 spring 可以通过类名 Autowiring 代理,为什么在添加 implements 时它不能执行此操作,特别是当 Autowiring 字段中未使用此接口(interface)时。

已更新

Spring-boot版本是2.0.3spring-core 版本是 5.0.7.RELEASE

最佳答案

With interfaces JDK dynamic proxies (interface based) are use, else you are using class based proxies. Newer Spring Boot versions force always to use class based proxies. Either way it uses proxies but with interfaces it uses interface only proxies and else uses class based (CGLIB) proxies.

来自M. Deinum comment .

确实如此,添加接口(interface)会导致jdk代理不是原始类的子类。

要强制子类代理子类,请将以下内容添加到 bean 声明中:

@Scope( proxyMode = ScopedProxyMode.TARGET_CLASS )

例如:

@Validated
@Component
@Scope( proxyMode = ScopedProxyMode.TARGET_CLASS )
public class MyImpl2 implements MyInterface{}

关于java - 为什么 @Validated + @Component + Implement 会在 Spring Boot 中导致类型误导性错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54087873/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com