java - spring chaining constructor with service injection -


i having class, this

public class testclass {     private testservice testservice;      public testclass() {         this(testservice);     }      @autowired(required = true)     public testclass(testservice testservice) {         this.testservice = testservice;     } } 

where default no-argument constructor mandatory, 'cause having structured factory design, there calling no-argument constructor don't want changes structure. went chaining constructor call argumented constructor default constructor. java throwing exception

cannot reference testservice before supertype constructor has been called,

i can solve exception having testservice static, here, red having static injection not idea.

can 1 advice me design solution on how can solve or call argumented constructor default constructor without having static injection.

you have 2 options:

field injection

add @autowired annotation field , throw away constructor arguments.

spring inject dependency using reflection. if in example default constructor after empty , constructor can throw away too, because java compiler create you.

pro: short code

constructor injection throw away parameterless constructor. spring provide dependency fine.

pro: code works fine without spring great, among other things tests. here more detailed explanation why prefer variation.

some additional comment:

  • always name classes first letter upper case. else makes code confusing read java developers.

  • you don't have factory there @ all. there various ways use factories spring, if interested.


Comments