Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 330
geoaxis Avatar asked Mar 07 '11 08:03

geoaxis


People also ask

Can we apply two annotations together?

It is also possible to use multiple annotations on the same declaration: @Author(name = "Jane Doe") @EBook class MyClass { ... } If the annotations have the same type, then this is called a repeating annotation: @Author(name = "Jane Doe") @Author(name = "John Smith") class MyClass { ... }

Can you apply more than one annotation?

As said by sfussenegger, this isn't possible. The usual solution is to build an "multiple" annotation, that handles an array of the previous annotation.

Can an annotation extend another annotation Java?

In Java SE 6, annotations cannot subclass one another, and an annotation is not allowed to extend/implement any interfaces.


Video Answer


1 Answers

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;
}
like image 143
JB Nizet Avatar answered Oct 12 '22 14:10

JB Nizet