Skip to content

@Autowired(required=false) and @Nullable cannot be used as meta-annotations on constructor parameters #33710

@bonnevAI

Description

@bonnevAI

Hello,

First of all, this is the first time I open an issue, so apologies in advance if I misunderstood the process, let me know and I will happily correct anything that can be :)

Consider the following annotation:

@Autowired(required = false) //Also works with @Nullable
@Retention(RUNTIME)
@Target({ METHOD, FIELD, PARAMETER, TYPE })
public @interface LazyInject {
}

If I use this annotation on an optional field it will behave as expected.
But, if I use it inside a constructor, I get the following exception:
springStack.log
This is in spring 5.3.37, but reading through the code, I think it still works like this in the latest version of spring.

To me this is an inconsistency which makes the framework harder to work with.
In my use case, I wanted to make a custom annotation and make it lazy by default, but could not because of this. This means the consumers of this annotation now have to specify by hand that it is lazy in constructors.

So for example, the following does not work:

public class MyService {

  @Autowired
  public MyService (@LazyInject MyRepository optionalRepo, AnotherDep anotherDep) {... }

}

the following works:

public class MyService {

  @Autowired
  public MyService (@Autowired(required = false) MyRepository optionalRepo, AnotherDep anotherDep) {... }

}

the following works:

public class MyService {

  @LazyInject
  MyRepository optionalRepo, 

  @Autowired
  public MyService (AnotherDep anotherDep) {... }

}

Thank you for your help!

Metadata

Metadata

Assignees

No one assigned

    Labels

    in: coreIssues in core modules (aop, beans, core, context, expression)status: invalidAn issue that we don't feel is valid

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions