0

Is it possible to mark with Autowired annotation several entities at once? So if have code like this:

@Autowired
private ClassA classA;

@Autowired
private ClassB classB;

@Autowired
private ClassC classC;

Can I replace it with something like this:

@Autowired
private ClassA classA, ClassB classB, ClassC classC;

I guess you got the idea.

Slava Semushin
  • 14,904
  • 7
  • 53
  • 69
IKo
  • 4,998
  • 8
  • 34
  • 54
  • 2
    One convention that has been found useful is to code following more-or-less the same standards and style as everyone else. Your suggestion is in conflict with this convention, and therefore isn't really a good idea, whether it is syntactically possible or not. Besides, I don't think that code is valid java, is it? You see -- if you cause confusion in your code through using unusual constructs then the chance of people understanding it at a glance is reduced -- so errors in this type of code will be harder to spot. – Software Engineer Mar 09 '17 at 16:40
  • I have a suggestion but since it doesn't directly answer your question I'm leaving it as a comment. Look at [constructor dependency injection](http://www.baeldung.com/constructor-injection-in-spring) which accomplishes what you want, and as of Spring 4.3 you can leave off `@Autowired`. I also agree with @Engineer-Dollery: what you're asking to do is not a good idea. There's nothing to be gained from it and is ambiguous at best (misleading at worst). I've used Spring for years and I don't know what would happen if you did that (neither do my coworkers). – Paul Mar 09 '17 at 16:47
  • To reassert what @Paul has said: you should be using constructor injection anyway -- the method you're using here is bad practice full-stop. If your service requires those three classes to work then they should be present as constructor arguments. Spring does not resolve you of your responsibility to build good OO models, and in OO if something is required then it should be impossible to create an object without it, which is what the constructor is for. – Software Engineer Mar 09 '17 at 17:05
  • I want to use it in my test. So I have a service which receives some request makes a record in db and sends response. I want to create a lets say 'module integration' test. So I send a request, check the record in db and response. That's why I need those three classes. Or for tests it's applied as well? – IKo Mar 09 '17 at 19:41

0 Answers0