11package org .lognet .springboot .grpc ;
22
3+ import java .util .ArrayList ;
4+ import java .util .List ;
35import java .util .Optional ;
46
7+ import io .grpc .ServerInterceptor ;
8+ import io .grpc .ServerInterceptors ;
9+ import io .grpc .ServerServiceDefinition ;
510import org .lognet .springboot .grpc .autoconfigure .GRpcServerProperties ;
611import org .springframework .beans .factory .DisposableBean ;
712import org .springframework .beans .factory .annotation .Autowired ;
@@ -40,7 +45,9 @@ public void run(String... args) throws Exception {
4045 if (BindableService .class .isAssignableFrom (grpcService .getClass ())) {
4146
4247 BindableService bindableService = BindableService .class .cast (grpcService );
43- serverBuilder .addService (bindableService );
48+
49+ ServerServiceDefinition definition = bindInterceptors (bindableService );
50+ serverBuilder .addService (definition );
4451 log .info ("'{}' service has been registered." , bindableService .getClass ().getName ());
4552 } else {
4653 throw new IllegalArgumentException (String .format ("%s should be of type %s" ,grpcService .getClass ().getName (), BindableService .class .getName ()));
@@ -53,6 +60,31 @@ public void run(String... args) throws Exception {
5360
5461 }
5562
63+ private ServerServiceDefinition bindInterceptors (BindableService bindableService ) {
64+ Class <? extends ServerInterceptor >[] interceptorClasses = bindableService .getClass ().getAnnotation (GRpcService .class ).interceptors ();
65+
66+ if (interceptorClasses .length == 0 ) {
67+ bindableService .bindService ();
68+ }
69+
70+ List <ServerInterceptor > interceptors = buildInterceptors (interceptorClasses );
71+ return ServerInterceptors .intercept (bindableService , interceptors );
72+ }
73+
74+ private List <ServerInterceptor > buildInterceptors (Class <? extends ServerInterceptor >[] classes ) {
75+ List <ServerInterceptor > interceptors = new ArrayList <>();
76+
77+ for (Class <? extends ServerInterceptor > clazz : classes ) {
78+ try {
79+ interceptors .add (clazz .newInstance ());
80+ } catch (InstantiationException | IllegalAccessException e ) {
81+ // TODO
82+ }
83+ }
84+
85+ return interceptors ;
86+ }
87+
5688 private void startDaemonAwaitThread () {
5789 Thread awaitThread = new Thread () {
5890 @ Override
0 commit comments