Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring @Autowire Multiple Objects

Tags:

spring

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

And do something like this:

@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...

like image 273
EdgeCase Avatar asked Feb 22 '23 04:02

EdgeCase


1 Answers

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;
}
like image 92
Chuprin Avatar answered Feb 23 '23 18:02

Chuprin