Reputation: 41097
Which do you prefer? In spring mvc, they use @Controller
for all Controller
classes. Could they have used some marker interface? Why did they select the annotation approach?
Better yet, they can have something similar to controller-scan
similar to component-scan
so any classes in the package can be assumed to a Controller class. Similarly service-scan
and repository-scan
can be defined in xml.
Upvotes: 1
Views: 3149
Reputation: 49572
I think technically the same effect would be possible with marker interfaces. The problem is that marker interfaces are limited to classes and cannot be used for attributes or methods.
Spring is using annotations for adding meta data to attributes (e.g. @Autowired
) or methods (e.g. @RequestMapping
or @Transactional
). So it is consistent to use the same approach for adding meta data to classes (like @Controller
or @Service
)
Note that Spring does not force you to use the provided annotations. @Controller
and @RequestMapping
are just the default way to define handler mappings. In theory you can come up with your own way of mapping incoming requests to method calls.
Upvotes: 8
Reputation: 3769
They both initially serve the same purpose; marking and discovering something.
Annotations are for the purpose of marking more direct. A marker interface actually defines a type, but when you declare a variable of said type there's nothing you can do with it. An annotation doesn't create a type, and it's up to the code processing the annotation to give a meaning to it.
Ultimately this is a matter of taste though.
Annotations do have the advantage of being able to store additional meta data. As in @Named("foo"). Marker interfaces have the advantage that you create collections which guarantee all items have the marker interface. E.g. there is no constraint that says a generic or variable type should have a specific annotation.
For annotations on methods vs methods in interfaces, there's the issue that methods in interfaces require an implementation (in Java 8 this will not strictly be required anymore) making classes quickly unwieldy, while annotations can be easier applied a la carte, but the compiler can't enforce a correct method signature. Meaning that some annotations require a method signature of say void foo(Bar bar), but this fact has to be looked up in the docs (if any).
Upvotes: 3