I have working spring web based application. Now I want to reuse its parts also for another project. Therefore I have two questions:
@Autowired
will work? I guess simple JAR on classpath is not sufficient - how to reference lib's application context etc? What other steps are needed?The approach I use is simply to ensure that application context fragments reside in a well-known location within the library jar file (personally I use META-INF/spring
). So I might have some common security configuration and beans in a file named META-INF/spring/common-security-context.xml
In your client application (the one using the library) you can include the services and beans from all your shared libraries by having an import like the following one inside your application-context:
<import resource="classpath*:META-INF/spring/*-context.xml" />
(note the asterisk after classpath). This will locate files whose names match the META-INF/spring/*-context.xml
pattern from any jar file or classpath root visible to the running application, and aggregate them into one logical context. Adjust the wildcard as you see fit.
Obviously you will need some strategy for avoiding bean/service name collisions that might occur if you start to use this widely.
You should use some kind of packaging that would tell what it depends on. A popular option is to use Maven packaging, providing pom.xml files that explain the dependencies. You'd then do Maven release of the app when you're done with it.
When taking it into use, you'd need to reference your shared configuration template in your apps spring configuration. You could import it directly:
<import resource="classpath*:/META-INF/path/to/otherAppContext.xml" />
This is assuming you actually want to share your spring context configuration. If you're providing reusable classes (only), there usually is no need to share context configs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With