问题
Let's take a basic example, say we have an entity class
@Entity
public class User {
}
and a DAO for dealing with the data:
public interface UserDao {
@Transactional
public void changeUser(User user);
}
@Repository
public class UserDaoImpl implements UserDao {
@PersistenceContext
private EntityManager em;
@Override
public void changeUser(User user) {
// ...
}
}
We have a main Maven Project that contains plenty other sub-projects, that we use for building multiple application (WARs, JARs etc.). Our framework of choice is Spring.
Each and every application needs the above entity / DAO and there are no per application customizations needed, everything remains the same. Every application has its own data source / persistence unit / transaction manager.
How can one best reuse the above entity / DAO across multiple applications? The entities need to be persisted in the application's database and we'd also need to reuse the app's transaction manager.
What did you do in similar situations?
回答1:
I would create separate Maven module that would contain entities and DAOs (you can even create two modules - one for entities and one for DAOs).
This module would be added as a dependency to any other application module (EJB or WAR modules), which needs DB layer. In Spring configuration you should properly define injection rules for datasource, persistence context, transaction manager, etc. In this way you would have common code with different configuration.
回答2:
I agree, modularizing classes is the easy part; automating configuration look-up/loading is the tricky part.
I suppose one could create an applicationContext.xml
for each module (listing beans, controllers etc. in it) and use the multiple configuration support to load them. But since obviously we can't name all XML files the same I would suggest the following:
Main project's web.xml
:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:auto-appctx-*.xml</param-value>
</context-param>
And a Maven/Ant script that would timestamp the XML file during packaging of each module/JAR like this:
<target name="copy-unique-appctx">
<timestamp/>
<copy src="src/resource/applicationContext.xml"
dest="build/classes/auto-appctx-${timestamp}.xml"/>
</target>
Note that this Ant target is typed "by memory" which is sketchy at the moment, and needs to be corrected (if the idea actually works).
来源:https://stackoverflow.com/questions/16065773/how-to-best-share-entity-classes-daos-across-multiple-pus