我有一个实用程序/常量类,其中包含一个Map<String, Authorizer>
带有Authorizer
几个不同实现的接口。我使用跨不同流的映射来获取包含一些String
(授权方法的名称)的对象,然后映射到特定Authorizer
的 ,然后完成一些授权。
我正在使用 Guice 来连接Authorizer
类,但这种方法使我无法使实用程序类(包含Map
)成为具有空私有构造函数的真正实用程序类。我有一个看起来很时髦的解决方法,让 Guice 和 Checkstyle 都满意,但我想知道是否有更好的方法。
我的实用程序类:
public final class Constants {
@Inject
private Constants() {}
public static final String AUTH_METHOD_ONE = "Auth1";
public static final String AUTH_METHOD_TWO = "Auth2";
@Singleton
@Inject
@Getter // For Checkstyle, as AUTH_METHODS isn't a true static final constant
private static Map<String, Authorizer> authMethods;
}
我的常量模块:
public class ConstantsModule extends AbstractModule {
@Override
public void configure() {
requestStaticInjection(Constants.class);
final MapBinder<String, Authorizer> mapBinder = MapBinder.newMapBinder(binder(), String.class, Authenticator.class);
mapBinder.addBinding(AUTH_METHOD_ONE).to(MethodOneAuthorizer.class);
mapBinder.addBinding(AUTH_METHOD_TWO).to(MethodTwoAuthorizer.class);
}
}
以及一个示例用法:
public class AuthorizationOrchestrator {
private static Authorizer getAuthorizer(final AuthorizationState state) {
return state.getMethods().stream()
.map(AuthorizationApproach::getAuthorizationApproachName)
.filter(Constants.getAuthMethods().keySet()::contains)
.findFirst()
.map(Constants.getAuthMethods()::get)
.orElse(null);
}
}
这种方法还需要在单元测试中使用一些 PowerMock。有没有更好的方法:
- 将授权方法的名称映射到一个
Authorizer
类,同时将映射保留在一个地方? - 将该
Constants
类用作真正的实用程序类,public static final Map<String, Authorizer> AUTH_METHODS
同时仍然能够将授权者注入Map
?