views:

128

answers:

4

I have annotated my classes with @Repository, @Resource, @Component, @Service annotations but these classes must run in 2 environments. The first environment is Spring 2.x based while the other has no spring at all. I'm sure the code will fail without the spring jars & I want to know ideas from you on how I can retain the annotations but still work in both environments

+1  A: 

For every annotation in Java, there is a corresponding class file. If you find out which annotations you use, you can copy the class files over to the other environment.

I'm not sure whether these classes are dependent on other classes aswel; they probably are not, since annotations are immutable data-only objects. If the class also has methods, you can re-compile (with the same Serialization ID) the annotation sources without the methods (i.e. only the fields) for use in the other environment.

Pindatjuh
A: 
seanhodges
I chose #2 and it works fine.
Jacques René Mesrine
Thank you Sean, that's gracious of you.
Hans Westerbeek
+3  A: 

To be able to use the annotations that you mention, or really, let Spring use them for you so you get the benefit, you need to use at least Spring 2.5.x, that's when they were introduced.

Furthermore, annotations are not required to be on the classpath. They will just be ignored. Since when you are using spring 2.0 there will be no code that tries to 'scan' for them.

Hans Westerbeek
You still have compile time dependencies on those annotations. And since your .class files have the annotations compiled in I would assume that you would need the annotations' .class files as well on your class path. Isn't that the case?
Magnus Jungsbluth
Nope :) to verify it I just tested. I created a tiny project, with a main(). The class is annotated with MyAnnotation that I wrote.I ran it on the commandline, then manually deleted the .class file for the annotation and ran it again. It still worked. Try it yourself :) Mind you my annotation was annotated it self with @Retention(RetentionPolicy.RUNTIME)
Hans Westerbeek
Very good to know indeed...
Magnus Jungsbluth
A: 

It wouldn't be spring if it forced you to make your classes directly dependent on it.

You can define your own annotations that serve the same purpose as the spring proved ones. I.e. define com.yourcompany....Component etc.

I assume that you use a <context:component-scan .../> somewhere in your spring config. Just add use-default-filters="false" and define your own filter to match your annotations.

Look for the PostProcessors that actually do the grunt work. They can be configured to use an alternate set of annotations. @Repository is examined by PersistenceExceptionTranslationPostProcessor. This PostProcessor can be configured to use your equivalent to the annotation.

Magnus Jungsbluth