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?
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;
}
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.
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.
精彩评论