0

If I have the following code:

Class A {

    @Autowired
    private B b;

    private List<B> bList =  ImmutableList.<B>builder().add(b).build();

}

even if the Spring is configured correctly for the package, for both class A and class B (verified by removing the ImmutableList line and using a method to set that variable instead and not changing any spring configuration), even then the above code with throw NullPointerException as b will not be initialized at that point I think. Is there any way to make Spring to initialize b first and then use that in the ImmutableListBuilder?

  • Move the list assignment to a method annotated with `@PostConstruct` – Jorge Campos Jul 30 '21 at 22:00
  • 2
    Field injection is done after class construction. I highly recommend to not use field injection (see, e.g., [this question](https://stackoverflow.com/questions/39890849/what-exactly-is-field-injection-and-how-to-avoid-it) from [T. Jung](https://stackoverflow.com/users/5444891/t-jung)) and use constructor injection instead. This also has the following, additional benefits: the fields can be declared as `final` - eases testability – Turing85 Jul 30 '21 at 22:00
  • Turing85@ so when the constructor is called, all the @Autowired dependencies will be available inside the constructor and I can use that for the list initialization.? Oh, great idea, let me try. I did not think of that as I assumed that if the field injection way is not working then constructor injection will also not work. Thank you for the answer. Also, agree on choice between field injection vs constructor injection – Arpit Krishna Jul 30 '21 at 22:13
  • Jorge Campos@ thank you for the answer, I will try to do that. But for my question, I wanted to know if there is a way where it could be done without needing to create a method. Sorry for the unclear question – Arpit Krishna Jul 30 '21 at 22:15
  • In the same class, not that I know of. Either you use my suggestion or Turing85's suggestion. The other way around is to create a config class and create a `@Bean` annotated method for this class A but it also defeat the purpose of your question. – Jorge Campos Jul 30 '21 at 22:17
  • After modifying the code as per @Turing85 suggestions, it worked but the problem is that instead of having just a single class to autowire, I have 10 class and these classes will keep increasing in number in future. Having to edit constructor every time will become cumbersome I think, perhaps I need to refactor the code. Thank you for all the help – Arpit Krishna Jul 30 '21 at 22:23
  • Some people believe that the signal you just found (of too many constructor methods) is a useful indication that you in fact do need just such refactoring. Note that in your example, you can simplify to `ImmutableList.copyOf(b)`, and the code you _actually_ provided is incorrect (you meant `addAll`). – chrylis -cautiouslyoptimistic- Jul 30 '21 at 23:55

0 Answers0