Spring constructor autoset and other field initialization

I have a Spring class where I outsource a service using a constructor, plus in the same constructor. I am initializing another 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 good practice ?, would the annotation @Autowired

have some effect on the otherFields

intialization process

+3


source to share


2 answers


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



Auto-posting is an easy way to create your object with the required dependencies, and your code is still your code.

+1


source


Not.

When Spring instantiates your class, it will find the constructor annotated with @Autowired

, collect the beans that match the arguments the constructor takes, and then invoke it with those beans as arguments.



It then scans all fields and methods in your class and injects beans into any fields that are annotated with @Autowired

. It will not touch on methods or fields that are not annotated.

+1


source







All Articles