-
Notifications
You must be signed in to change notification settings - Fork 5
Integration
JayWire provides the StandaloneModule by default which can be used to wire
components together for a standalone program, using singleton and threadlocal scopes. However, because all scopes
are just normal objects these scopes can be replaced/adapted/extended to integrate with the environment they are in.
Since all modules (or module framgents) are usually written as interfaces (see Modularisation why that is the case), it is easy to provide an environment-specific implementation of the used scopes later, at the top of the module hierarchy.
At the top of the module hierarchy, methods for the different scopes can be simply overridden to provide customized / alternative scope implementations like this:
public class MyAppModule extends StandaloneModule implements ModuleA, ModuleB, ModuleC {
private Scope singletonScope = new MyCustomSingletonScope();
@Override
public Scope getSingletonScope() {
return singletonScope;
}
}This way all modules that use singleton scope will use the provided one automatically.
By default JayWire comes with a ServletRequestScope and a HttpSessionScope implementation of the request and
session scopes. These both have methods to set and clear the underlying (thread local) ServletRequest and HttpSession objects.
Both assume, that at the beginning of a request the appropriate object is set, and at the end of the request both of
them are cleared. In between all objects that are created are directly stored in the request or session objects, the
scopes themselves do not store any references to objects.
To provide an integration with some specific web framework, you can subclass the StandaloneModule and extend it with
listeners, handlers or call-backs to call these methods from the chosen web framework. For example the Spark integration
looks like this:
public class SparkModule extends StandaloneModule
implements ServletRequestScopeModule, HttpSessionScopeModule {
...
public void addRoutes() {
Spark.before((request, response) -> {
getServletRequestScope().setServletRequest(request.raw());
getHttpSessionScope().setHttpSession(request.session(true).raw());
});
Spark.after((request, response) -> {
getServletRequestScope().clearServletRequest();
getHttpSessionScope().clearHttpSession();
});
}
}The before and after callbacks are called by Spark automatically before and after a request is handled, so it is perfect for opening and closing the request and session scope. Remember: both of these scopes store their underlying object as a thread-local, so it is safe to directly set the current request and session object.
Please check the wiki for existing integrations.