Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to package spring based library for reuse?

Tags:

java

spring

I have working spring web based application. Now I want to reuse its parts also for another project. Therefore I have two questions:

  1. What is the recommended way to pack such functionality as reusable library? JAR file with application context XML inside or JAR + extra XML? Something else?
  2. How to incorporate such library to another Spring (web-) based project (different namespace - package) so that e.g. @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?
like image 655
sodik Avatar asked Oct 01 '13 12:10

sodik


2 Answers

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.

like image 55
darrend Avatar answered Nov 16 '22 22:11

darrend


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.

like image 2
eis Avatar answered Nov 16 '22 23:11

eis