Modularization for Spring Apps Using Z2
Using the integration features in Z2 Components and Spring Beans the Z2 component model can be conveniently used to built re-usable, shared modules using the Spring framework and the concept of z2 projects.
As compared to assembly of monolithic applications from build artifacts this approach has several benefits:
For example, a module that uses JPA persistence and that is used by several web applications will need to initialize only once – saving significant time and memory resources. Spring beans implementing application services can be singletons on the VM level and optimize resource usage, e.g. for caches, connection pooling etc.
Building resuable modules is very easy. Essentially you declare an application context as a z2 component as described above and expose beans that implement services or provide access to entity managers and so on by bean components, again as described above to expose features implemented in a z2 project. In other words: Z2 projects are the right choice for modules of a solution that provide any number of re-usable or private resources, a public API and a private implementation.
In the illustration below, the domain module would be modeled as a Z2 project exposing a Spring bean "bean" of the application context "appctxt" that is defined as a Spring application context with a JPA persistence unit. The web module simply contains a web app "web" and its Java component has a private reference to the domain module.
The sample application in the z2@Spring repository has two modules:
- A service module samples.spring.simplemodules.services that provides reusable services and has an API. It could also contain data source definitions, schema migrations, schedulable jobs etc.
- A frontend module samples.spring.simplemodules.frontend that contains a web app exposing functionality implemented over the service module.
In samples.spring.simplemodules.services, the computations component is actually a bean from the application service of the module, defined in the implementation part of samples.spring.simplemodules.services/java. It implements the service interface IComputationService.,
The Web application samples.spring.simplemodules.frontend/web has an application context that binds the other modules component via the Z2 Component Factory bean:
<bean id="computations" class="com.zfabrik.springframework.ComponentFactoryBean"> <property name="componentName" value="samples.spring.simplemodules.services/computations"/> <property name="className" value="samples.services.IComputationService"/> </bean>