geoaxis
geoaxis

Reputation: 1560

Applying same annotation on multiple fields

Is it possible to apply same annotation on multiple fields (if there are many private fields and it just looks awkward to annotate them all.

So What I have is like

@Autowired private BlahService1 blahService1;
@Autowired private BlahService2 blahService2;
@Autowired private BlahService3 blahService3;

and so on

I tried the following but it won't work

@Autowired{     
   private BlahService1 blahService1;       
   private BalhService2 blahService2;   
}

Some thing fancy with custom annotations perhaps?

Upvotes: 7

Views: 3999

Answers (3)

Ankur
Ankur

Reputation: 788

You can try extending AutoWired annotation interface with setting default values of fields, setting its target type to fields, and whenever it is not required you can turn it of by passing appropriate values to annotations on only those fields.

Upvotes: 0

Joachim Sauer
Joachim Sauer

Reputation: 308031

There's nothing built-in to the language that allows that kind of multi-annotations.

Many frameworks however opt to allow some kind of "default-annotation" on the class level.

For example, it would be possible for the framework to allow an @Autowired annotation at the class level to imply that each field should be auto-wired. That's entirely up to the framework to implement, however.

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691735

No, but you could annotate your constructor rather than your fields. This would have the additional benefit to make your class more easily testable, by injecting mock dependencies when constructing the instance to test (which is the main reason why dependency injection is useful) :

@Autowired
public MyClass(BlahService1 blahService1, BlahService2 blahService2, BlahService3 blahService3) {
    this.blahService1 = blahService1;
    this.blahService2 = blahService2;
    this.blahService3 = blahService3;
}

Upvotes: 7

Related Questions