我将 class C 的对象标记为“@Autowired(required = false)”,但 spring 仍在尝试查找其实例

I am marking my object of class C as a “@Autowired(required = false)“, still spring is trying to find its instance

我将 class C 的对象标记为“@Autowired(required = false)”,但 spring 仍在尝试查找其实例,我收到以下错误

原因:org.springframework.beans.factory.NoSuchBeanDefinitionException:没有符合条件的 class C

类型的 bean
@Component
@Slf4j
public class Foo {

    private A aa;
    private B bb;
    private C cc;

    public Foo(@Autowired final A aa,
               @Autowired final B bb,
               @Autowired(required = false) final C cc) {
        this.aa = aa;
        this.bb = bb;
        this.cc = cc;
    }

来自documentation of @Autowired

...

Autowired Parameters

Although @Autowired can technically be declared on individual method or constructor parameters since Spring Framework 5.0, most parts of the framework ignore such declarations. The only part of the core Spring Framework that actively supports autowired parameters is the JUnit Jupiter support in the spring-test module (see the TestContext framework reference documentation for details).

Multiple Arguments and 'required' Semantics

In the case of a multi-arg constructor or method, the required() attribute is applicable to all arguments. Individual parameters may be declared as Java-8 style Optional or, as of Spring Framework 5.0, also as @Nullable or a not-null parameter type in Kotlin, overriding the base 'required' semantics.

...

所以简而言之,这意味着我们应该用 @Autowired 注释构造函数并用 @Nullable 注释可选参数或使它们成为 Optionals.