Scrollbar |
---|
Services consist of two main parts: a service interface and a service implementation.
...
Tapestry IoC waits until the last possible moment to realize the service: that's defined as when a method of the service is invoked. Tapestry is thread-safe, so even in a heavily contested, highly threaded environment (such as a servlet container or application server) things Just Work.
Anchor | ||||
---|---|---|---|---|
|
Service Builder Methods
Tapestry doesn't know how to instantiate and configure your service; instead it relies on you to provide the code to do so, in a service builder method, a method whose name is (or starts with) "build":
Code Block | ||
---|---|---|
| ||
package org.example.myapp.services;
public class MyAppModule
{
public static Indexer build()
{
return new IndexerImpl();
}
} |
...
Every module may have an optional, static bind() method which is passed a ServiceBinder. Services may be registered with the container by "binding" a service interface to a service implementation:
Code Block | ||||
---|---|---|---|---|
| ||||
package org.example.myapp.services;
import org.apache.tapestry5.ioc.ServiceBinder;
public class MyAppModule
{
public static void bind(ServiceBinder binder)
{
binder.bind(Indexer.class, IndexerImpl.class);
}
} |
...
Following the convention over configuration principle, the autobuilding of services can be even less verbose. If a service interface is passed as a single argument to the bind() method, Tapestry will try to find an implementation in the same package whose name matches the name of the service interface followed by the suffix Impl.
Code Block | ||||
---|---|---|---|---|
| ||||
package org.example.myapp.services;
import org.apache.tapestry5.ioc.ServiceBinder;
public class MyAppModule
{
public static void bind(ServiceBinder binder)
{
binder.bind(Indexer.class);
}
} |
...
This can be overridden by adding the @ServiceId annotation to the service builder method:
Code Block | ||||
---|---|---|---|---|
| ||||
@ServiceId("FileSystemIndexer")
public static Indexer buildIndexer(@InjectService("FileSystem") FileSystem fileSystem)
{
. . .
} |
Another option is to add the service id to the method name, after "build", for example:
Code Block | ||||
---|---|---|---|---|
| ||||
public static Indexer buildFileSystemIndexer(@InjectService("FileSystem") FileSystem fileSystem)
{
. . .
} |
...
For autobuilt services, the service id can be specified by placing the @ServiceId annotation directly on a service implementation class.
Code Block | ||||
---|---|---|---|---|
| ||||
@ServiceId("FileSystemIndexer")
public class IndexerImpl implements Indexer
{
...
} |
When the service is bound, the value of the annotation is used as id:
Code Block | ||||
---|---|---|---|---|
| ||||
binder.bind(Indexer.class, IndexerImpl.class); |
This id can be overriden again by calling the method withId(String):
Code Block | ||||
---|---|---|---|---|
| ||||
binder.bind(Indexer.class, IndexerImpl.class).withId("FileSystemIndexer"); |
...
For example, let's say the Indexer needs a JobScheduler to control when it executes, and a FileSystem to access files and store indexes.
Code Block | ||||
---|---|---|---|---|
| ||||
public static Indexer build(JobScheduler scheduler, FileSystem fileSystem) { IndexerImpl indexer = new IndexerImpl(fileSystem); scheduler.scheduleDailyJob(indexer); return indexer; } |
Tapestry assumes that parameters to builder methods are dependencies; in this example it is able to figure out what services to pass in based just on the type (later we'll see how we can fine tune this with annotations, when the service type is not sufficient to identify a single service).
...
Note that we don't invoke those service builder methods ... we just "advertise" (via naming convention or annotation) that we need the named services. Tapestry IoC will provide the necessary proxies and, when we start to invoke methods on those proxies, will ensure that the full service, including its interceptors and its dependencies, are ready to go. Again, this is done in a thread-safe manner.
What happens if there is more than one service that implements the JobScheduler interface, or the FileSystem interface? You'll see a runtime exception, because Tapestry is unable to resolve it down to a single service. At this point, it is necessary to disambiguate the link between the service interface and one service. One approach is to use the @InjectService annotation:
Code Block | ||||
---|---|---|---|---|
| ||||
public static Indexer build(@InjectService("JobScheduler") JobScheduler scheduler, @InjectService("FileSystem") FileSystem fileSystem) { IndexerImpl indexer = new IndexerImpl(fileSystem); scheduler.scheduleDailyJob(indexer); return indexer; } |
If you find yourself injecting the same dependencies into multiple service builder (or service decorator) methods, you can cache dependency injections in your module, by defining a constructor. This reduces duplication in your module.
...
We can associate those two JobSchedulers with two annotations.
Code Block | ||||
---|---|---|---|---|
| ||||
@Target(
{ PARAMETER, FIELD })
@Retention(RUNTIME)
@Documented
public @interface Clustered
{
}
@Target(
{ PARAMETER, FIELD })
@Retention(RUNTIME)
@Documented
public @interface InProcess
{
}
public class MyModule
{
public static void bind(ServiceBinder binder)
{
binder.bind(JobScheduler.class, ClusteredJobSchedulerImpl.class).withId("ClusteredJobScheduler").withMarker(Clustered.class);
binder.bind(JobScheduler.class, SimpleJobSchedulerImpl.class).withId("InProcessJobScheduler").withMarker(InProcess.class);
}
} |
...
To get the right version of the service, you use one of the annotations:
Code Block | ||||
---|---|---|---|---|
| ||||
public class MyServiceImpl implements MyService
{
private final JobScheduler jobScheduler;
public MyServiceImpl(@Clustered JobScheduler jobScheduler)
{
this.jobScheduler = jobScheduler;
}
. . .
} |
...
With a service builder method, you use the @Marker @Marker annotation:
Code Block | ||||
---|---|---|---|---|
| ||||
@Marker(Clustered.class)
public JobScheduler buildClusteredJobScheduler()
{
return . . .;
} |
...
A special marker interface, @Local@Local, indicates a dependency that should only be resolved using services from within the same module.
...
Instead, the injections occur on constructor for the implementation class:
Code Block | ||||
---|---|---|---|---|
| ||||
package org.example.myapp.services; import org.apache.tapestry5.ioc.annotations.InjectService; public class IndexerImpl implements Indexer { private final FileSystem fileSystem; public IndexerImpl(@InjectService("FileSystem") FileSystem fileSystem) { this.fileSystem = fileSystem; } . . . } |
...
Once thing that is not a good idea is to pass in another service, such as JobScheduler in the previous example, and pass this
from a constructor:
Code Block | ||||
---|---|---|---|---|
| ||||
package org.example.myapp.services; import org.apache.tapestry5.ioc.annotations.InjectService; public class IndexerImpl implements Indexer { private final FileSystem fileSystem; public IndexerImpl(@InjectService("FileSystem") FileSystem fileSystem, @InjectService("JobScheduler") JobScheduler scheduler) { this.fileSystem = fileSystem; scheduler.scheduleDailyJob(this); // Bad Idea } . . . } |
Understanding why this is a bad idea involves a long detour into inner details of the Java Memory Model. The short form is that other threads may end up invoking methods on the IndexerImpl instance, and its fields (even though they are final, even though they appear to already have been set) may be uninitialized.
Field Injection
The @Inject and @InjectService annotations may be used on instance fields of a service implementation class, as an alternative to passing dependencies of the service implementation in via the constructor.
Note that only dependencies are settable this way; if you want resources, including the service's configuration, you must pass those through the constructor. You are free to mix and match, injecting partially with field injection and partially with constructor injection.
Caution: injection via fields uses reflection to make the fields accessible. In addition, it may not be as thread-safe as using the constructor to assign to final fields.
Code Block | ||||
---|---|---|---|---|
| ||||
package org.example.myapp.services;
import org.apache.tapestry5.ioc.annotations.InjectService;
public class IndexerImpl implements Indexer
{
@InjectService("FileSystem")
private FileSystem fileSystem;
. . .
} |
...
This is useful when a service needs to keep request specific state, such as information extracted from the HttpServletRequest (in a web application). The default singleton model would not work in such a multi threaded multithreaded environment. Using perthread on select services allows state to be isolated to those services. Because the dispatch occurs inside the proxy, you can treat the service as a global, like any other.
...
The service implementation class may include the @Scope @Scope annotation. This is generally the preferred way to specify scope.
In addition, it is possible to specify the scope when binding the service:
Code Block | ||||
---|---|---|---|---|
| ||||
bind(MyServiceInterface.class, MyServiceImpl.class).scope(IOCConstantsScopeConstants.PERTHREAD_SCOPE); |
Eager Loading Services
Services are normally created only as needed (per the scope discussion above).
This can be tweaked slightly; by adding the @EagerLoad annotation to the service builder method, Tapestry will instantiate the service when the Registry is first created.
...
You may also specify eager loading explicitly when binding the service:
Code Block | ||||
---|---|---|---|---|
| ||||
bind(MyServiceInterface.class, MyServiceImpl.class).eagerLoad(); |
...
No annotation is needed for these cases.
See also service configuration for additional special cases of resources that can be injected.
...
Example:
Code Block | ||||
---|---|---|---|---|
| ||||
public static Indexer build(String serviceId, Log serviceLog, JobScheduler scheduler, FileSystem fileSystem) { IndexerImpl indexer = new IndexerImpl(serviceLog, fileSystem); scheduler.scheduleDailyJob(serviceId, indexer); return indexer; } |
...
Further, ServiceResources includes an autobuild() method that allows you to easily trigger the construction of a class, including dependencies. Thus the previos example could be rewritten as:
Code Block | ||||
---|---|---|---|---|
| ||||
public static Indexer build(ServiceResources resources, JobScheduler jobScheduler) { IndexerImpl indexer = resources.autobuild(IndexerImpl.class); scheduler.scheduleDailyJob(resources.getServiceId(), indexer); return indexer; } |
...
If the @InjectService annotation is not present, and the parameter type does not exactly match a resource type, then object injection occurs. Object injection will find the correct object to inject based on a number of (extensible) factors, including the parameter type and any additional annotations on the parameter.
Every once and a while, you'll have a conflict between a resource type and an object injection. For example, the following does not work as expected:
Code Block | ||||
---|---|---|---|---|
| ||||
public static Indexer build(String serviceId, Log serviceLog, JobScheduler scheduler, FileSystem fileSystem, @Value("${index-alerts-email}") String alertEmail) { IndexerImpl indexer = new IndexerImpl(serviceLog, fileSystem, alertEmail); scheduler.scheduleDailyJob(serviceId, indexer); return indexer; } |
It doesn't work because type String always gets the service id, as a resource (as with the serviceId parameter). In order to get this to work, we need to turn off the resource injection for the alertEmail parameter. That's what the @Inject annotation does:
Code Block | ||||
---|---|---|---|---|
| ||||
public static Indexer build(String serviceId, Log serviceLog, JobScheduler scheduler, FileSystem fileSystem, @Inject @Value("${index-alerts-email}") String alertEmail) { IndexerImpl indexer = new IndexerImpl(serviceLog, fileSystem, alertEmail); scheduler.scheduleDailyJob(serviceId, indexer); return indexer; } |
Here, the alertEmail parameter will receive the configured alerts email (see the symbols documentation for more about this syntax) rather than the service id.
...
Service Id | Service Interface |
ClassFactory | |
LoggerSource | |
RegistryShutdownHub | |
PerthreadManager |
...
With Tapestry IoC, this is not even considered a special case:
Code Block | ||||
---|---|---|---|---|
| ||||
public static Indexer buildIndexer(JobScheduler scheduler, FileSystem fileSystem) { IndexerImpl indexer = new IndexerImpl(fileSystem); scheduler.scheduleDailyJob(indexer); return indexer; } public static FileSystem buildFileSystem(Indexer indexer) { return new FileSystemImpl(indexer); } |
...
This approach can be very powerful. For example, it can be used it to break apart untestable monolithic code into two mutually dependent halves, each of which can be unit tested.
The exception to this rule is a service that depends on itself during construction. This can occur when (indirectly, through other services) building the service tries to invoke a method on the service being built. This can happen when the service implementation's constructor invoke methods on service dependencies passed into it, or when the service builder method itself does the same. This is actually a very rare case and difficult to illustrate.
Scrollbar |
---|