Spring constructor autowiring and initializing other field

I having a Spring class, where I am autowiring a service using constructor, plus in the same constructor I am intializing other field of the same class.

@Component
class Converter {
  private TestService testService;
  private Interger otherFields;
  @Autowired
  public Converter(TestService testService) {
     this.testService = testService;
     this.otherFields = new Integer(10);
  }
}

My Functionality is working fine, but is it a good practice?, would @Autowired annotation have any impact on otherFields intialization process

Upvotes: 3

Views: 2383

Answers (2)

Raniz
Raniz

Reputation: 11123

No.

When Spring is instantiating your class it will locate the constructor annotated with @Autowired, collect the beans that corresponds to the arguments the constructor takes and then invoke it with those beans as arguments.

It will then scan through all fields and methods in your class and inject beans into any fields that are annotate with @Autowired. It will not touch methods or fields that are not annotated.

Upvotes: 1

Praba
Praba

Reputation: 1381

It shouldn't. Back in the xml days, when you want to pass on an argument to a constructor, you mentioned your ref bean for the constructor arg. This just means that you must have a constructor that takes the specified bean type as an argument. It doesn't really matter what you add in the constructor, as long as you are creating a valid object through the constructor (though this is just normal java programming and nothing to do with Spring).

Auto-wiring is just an easy way to create your object with the necessary dependencies and your code is still your code.

Upvotes: 1

Related Questions