Donnerstag, 27. Oktober 2011

Spring DI with Java Standard Annotations

In Spring it is easy to use the Java annotations for dependency injection (JSR 330), the Java annotation for post construct and pre destroy (JSR 250) and the Java API and Annotations for validation (JSR 303).

Why should I use this standard APIs and annotation in a Spring based application? Because when using this standards, the code has only dependency on standard APIs (javax). And the code could also be used in another implementation e.g. of the JSR 330.

Here a simple code snippet, which shows how to use this three Java standards in a spring bean.



And here the spring context configuration.


You could also mix the Spring annotations with the JSR 330 annotation. I think a good strategy is to use the JSR 330 annotation when every its possible and makes sense. In some cases you would use the spring specific annotations.

Which annotations do you prefer to use in a Spring application?

For more details see the spring documentation:
http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/