Spring @Autowire Objetos múltiples

I like code to be visually easy to read (subjective, I know). Is there a a way in Spring to take the first form of code

@Autowired
private O1 o1
@Autowired
private O2 o2
@Autowired
private O3 o3

Y haz algo como esto:

@Autowired
private O1 o1
private O2 o2
private O3 o3
@Endautowire

I would find the code to be less cluttered. I know I am being trivial and picky, but...

preguntado el 10 de marzo de 12 a las 15:03

5 Respuestas

You can use constructor to inject all objects with one annotation:

private O1 o1;
private O2 o2;
private O3 o3;

@Autowired
public ClassA(O1 o1, O2 o2, O3 o3) {
    this.o1 = o1;
    this.o2 = o2;
    this.o3 = o3;
}

respondido 11 mar '12, 08:03

There was times when people use to declare variable like,

int i1, i2, i3;

This is no longer considered as a best practice and declaring each of them separately increases the readability.

Coming to your question, as as mrembisz told it it has to happen, need to happen in source files. Other wise the java compiler should change to handle such a scenario.

Coming to readability, your solution will only increase the code clutter and reduce the readability, suppose I have 10 beans injected, every time I need to see above and below the code to know if it is auto-wired or not.

So, I doubt it worth spend time doing or not.

respondido 11 mar '12, 07:03

It is possible only with a preprocessor for java sources. But totally not worth it in my opinion.

respondido 10 mar '12, 16:03

Not how you want with annotations.

You could make a uber type that takes these three, and add that type here. Id only do that if you find yourself in this situation many time, or if it truly reflects a concept in your application.

respondido 10 mar '12, 15:03

I had the same thought as the original poster, but after having read the answers, I completely agree with the consensus that it is better to individually annotate members. I am upvoting the original question because it is a good question in spite of its bad underlying assumption and because it resulted in even better answers.

Respondido el 04 de diciembre de 13 a las 20:12

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.