1 package org.apache.onami.guava.eventbus;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import static com.google.common.base.Preconditions.checkArgument;
23 import static com.google.inject.matcher.Matchers.any;
24
25 import static com.google.inject.name.Names.named;
26
27 import com.google.common.eventbus.EventBus;
28 import com.google.inject.AbstractModule;
29 import com.google.inject.TypeLiteral;
30 import com.google.inject.matcher.Matcher;
31 import com.google.inject.spi.InjectionListener;
32 import com.google.inject.spi.TypeEncounter;
33 import com.google.inject.spi.TypeListener;
34
35
36
37
38
39
40 public abstract class EventBusModule
41 extends AbstractModule
42 {
43
44 protected BusMatcher bindBus( final String identifier )
45 {
46 checkArgument( identifier != null, "Event bus identifier must be not null" );
47
48 return new BusMatcher()
49 {
50
51 public void toAnyBoundClass()
52 {
53 to( any() );
54 }
55
56 public void to( Matcher<? super TypeLiteral<?>> matcher )
57 {
58 checkArgument( matcher != null, "Event bus matcher must be not null" );
59
60 final EventBus eventBus = new EventBus( identifier );
61
62 bind( EventBus.class ).annotatedWith( named( identifier ) ).toInstance( eventBus );
63
64 bindListener( matcher, new TypeListener()
65 {
66 public <I> void hear( TypeLiteral<I> typeLiteral, TypeEncounter<I> typeEncounter )
67 {
68 typeEncounter.register( new InjectionListener<I>()
69 {
70 public void afterInjection( I injectee )
71 {
72 eventBus.register( injectee );
73 }
74 } );
75 }
76 } );
77 }
78
79 };
80 }
81
82 }