下面列出了怎么用com.google.inject.Stage的API类实例代码及写法,或者点击链接到github查看源代码。
protected Injector getInjector() {
boolean success = false;
final StringWriter errorOut = new StringWriter();
PrintWriter errorWriter = new PrintWriter(errorOut);
try {
this.injector = Guice.createInjector(Stage.PRODUCTION, this.getModules());
success = true;
} catch (Exception e){
System.err.println("[HMDM-INITIALIZER]: Unexpected error during injector initialization: " + e);
e.printStackTrace();
e.printStackTrace(errorWriter);
}
if (success) {
System.out.println("[HMDM-INITIALIZER]: Application initialization was successful");
onInitializationCompletion(null);
} else {
System.out.println("[HMDM-INITIALIZER]: Application initialization has failed");
onInitializationCompletion(errorOut);
}
return injector;
}
public static @NotNull Injector persistenceInjector(
final @NotNull SystemInformation systemInformation,
final @NotNull MetricRegistry metricRegistry,
final @NotNull HivemqId hiveMQId,
final @NotNull FullConfigurationService configService) {
final ImmutableList.Builder<AbstractModule> modules = ImmutableList.builder();
modules.add(new SystemInformationModule(systemInformation),
new ConfigurationModule(configService, hiveMQId),
new LazySingletonModule(),
LifecycleModule.get(),
new PersistenceMigrationModule(metricRegistry, configService.persistenceConfigurationService()));
return Guice.createInjector(Stage.PRODUCTION, modules.build());
}
@Test
public void test_ssl_factory_same() {
final Injector injector = Guice.createInjector(Stage.PRODUCTION, new SecurityModule(), new AbstractModule() {
@Override
protected void configure() {
bind(EventExecutorGroup.class).toInstance(mock(EventExecutorGroup.class));
bind(ShutdownHooks.class).toInstance(mock(ShutdownHooks.class));
bindScope(LazySingleton.class, LazySingletonScope.get());
}
});
final SslFactory instance1 = injector.getInstance(SslFactory.class);
final SslFactory instance2 = injector.getInstance(SslFactory.class);
assertSame(instance1, instance2);
}
@Test
public void test_topic_matcher_not_same() {
final Injector injector = Guice.createInjector(Stage.PRODUCTION,
new HiveMQMainModule(),
new AbstractModule() {
@Override
protected void configure() {
bind(EventExecutorGroup.class).toInstance(Mockito.mock(EventExecutorGroup.class));
}
});
final TopicMatcher instance1 = injector.getInstance(TopicMatcher.class);
final TopicMatcher instance2 = injector.getInstance(TopicMatcher.class);
assertNotSame(instance1, instance2);
}
@Override
protected void configure() {
// @InjectorScoped annotation
install(new InjectorScopeModule());
// Provide a global, catch-all exception handler
bind(LoggingExceptionHandler.class).in(Singleton.class);
bind(ExceptionHandler.class).to(LoggingExceptionHandler.class);
bind(new TypeLiteral<ExceptionHandler<Throwable>>(){}).to(LoggingExceptionHandler.class);
bind(Thread.UncaughtExceptionHandler.class).to(LoggingExceptionHandler.class);
// Evil decorator thing
// Create it manually so we can use it before the injector is ready
bind(DecoratorFactory.class).toInstance(DecoratorFactory.get());
install(new NumberFactory.Manifest());
install(new ParsersManifest());
requestStaticInjection(SystemFutureCallback.class);
if(currentStage() == Stage.DEVELOPMENT) {
// This is useful, but it makes the LeakDetector unhappy
//install(new RepeatInjectionDetector());
}
}
public Client(@NonNull Path filePath, @NonNull Config config, boolean cleanRun, @NonNull List<?> listeners) {
this.filePath = checkFile(filePath);
this.cleanRun = cleanRun;
this.config = config;
Injector injector = Guice.createInjector(
Stage.PRODUCTION,
new ConfigurationModule(ConfigValidator.checkValid(config.withFallback(ConfigFactory.load()))),
new JpaRepositoryModule(),
new ServiceModule()
);
persistService = injector.getInstance(PersistService.class);
persistService.start();
handlerType = injector.getInstance(MovieHandler.Type.class);
handlerChain = injector.getInstance(MovieHandler.class);
importProgressService = injector.getInstance(ImportProgressService.class);
eventBus = new EventBus();
listeners.forEach(eventBus::register);
}
@Override
protected Injector getInjector() {
// Create injector
Injector injector = Guice.createInjector(Stage.PRODUCTION,
new EnvironmentModule(environment),
new LogModule(environment),
new ExtensionModule(environment),
new RESTServiceModule(sessionMap),
new TunnelModule()
);
// Inject any annotated members of this class
injector.injectMembers(this);
return injector;
}
private GuiceBundle(final Class<T> configClass,
final ImmutableSet<Module> guiceModules,
final ImmutableSet<DropwizardAwareModule<T>> dropwizardAwareModules,
final Stage guiceStage,
final boolean allowUnknownFields,
final boolean enableGuiceEnforcer,
final InjectorFactory injectorFactory) {
this.configClass = configClass;
this.guiceModules = guiceModules;
this.dropwizardAwareModules = dropwizardAwareModules;
this.guiceStage = guiceStage;
this.allowUnknownFields = allowUnknownFields;
this.enableGuiceEnforcer = enableGuiceEnforcer;
this.injectorFactory = injectorFactory;
}
@Override
public void contextInitialized(ServletContextEvent sce) {
/*
* TODO switch to production
*/
injector = Guice.createInjector(Stage.DEVELOPMENT,
new DevelopersSharedModule(),
new DevelopersSharedServletModule(),
new BackendServletModule());
logger.info("created injector");
super.contextInitialized(sce);
return;
}
private void renderGuiceWeb(final TreeNode filter) throws Exception {
final List<String> servlets = new ArrayList<>();
final List<String> filters = new ArrayList<>();
for (Element element : Elements.getElements(Stage.TOOL, modules)) {
if (!(element instanceof Binding)) {
continue;
}
@SuppressWarnings("unchecked") final WebElementModel model =
(WebElementModel) ((Binding) element).acceptTargetVisitor(VISITOR);
if (model == null) {
continue;
}
final String line = renderGuiceWebElement(model, element);
if (model.getType().equals(WebElementType.FILTER)) {
filters.add(line);
} else {
servlets.add(line);
}
}
renderGucieWebElements(servlets, filters, filter);
}
@Override
protected void configure() {
checkHkFirstMode();
final EnumSet<DispatcherType> types = context.option(GuiceFilterRegistration);
final boolean guiceServletSupport = !types.isEmpty();
// injector not available at this point, so using provider
final InjectorProvider provider = new InjectorProvider(application);
install(new GuiceBindingsModule(provider, guiceServletSupport));
final GuiceFeature component =
new GuiceFeature(provider, context.stat(), context.lifecycle(), context.option(UseHkBridge));
bind(InjectionManager.class).toProvider(component);
// avoid registration when called within guice report
if (currentStage() != Stage.TOOL) {
environment.jersey().register(component);
}
if (guiceServletSupport) {
install(new GuiceWebModule(environment, types));
}
}
@Override
protected Injector getInjector() {
// Create injector
Injector injector = Guice.createInjector(Stage.PRODUCTION,
new EnvironmentModule(environment),
new LogModule(environment),
new ExtensionModule(environment),
new RESTServiceModule(sessionMap),
new TunnelModule()
);
// Inject any annotated members of this class
injector.injectMembers(this);
return injector;
}
@Test
public void testModuleMapping() throws Exception {
Map<String, String> props = new HashMap<String, String>() ;
props.put("hello", "Hello Property") ;
props.put("registry.connect", "127.0.0.1:2181") ;
props.put("registry.db-domain", "/scribengin/v2") ;
Injector container1 =
Guice.createInjector(Stage.PRODUCTION, new CloseableModule(), new Jsr250Module(), new MycilaJmxModuleExt("test-domain"), new AppModule(props));
Hello hello = container1.getInstance(Hello.class);
hello.sayHello();
MycilaJMXService service = container1.getInstance(MycilaJMXService.class);
service.increment(1);
//MycilaJMXService service2 = container2.getInstance(MycilaJMXService.class);
//service2.increment(1);
Assert.assertTrue(container1.getInstance(Pojo.class) == container1.getInstance(Pojo.class));
Pojo pojo = container1.getInstance(Pojo.class) ;
Assert.assertEquals("127.0.0.1:2181", pojo.getConnect());
Assert.assertEquals("/scribengin/v2", pojo.getDbDomain());
container1.getInstance(CloseableInjector.class).close();
}
static SmartAppDefinition smartapp(Consumer<BindingsSpec> consumer) {
List<Module> modules = new ArrayList<>();
DefaultBindingsSpec bindingsSpec = new DefaultBindingsSpec(modules);
consumer.accept(bindingsSpec);
Injector injector = createInjector(Stage.PRODUCTION, modules);
return new GuiceSmartAppDefinition(injector);
}
@Test
public void test_lazy_singleton_lazy_inition() throws Exception {
Guice.createInjector(Stage.PRODUCTION, new LazySingletonModule(),
new AbstractModule() {
@Override
protected void configure() {
bind(LazySingletonClass.class);
bind(StandardSingleton.class);
}
});
assertEquals(true, StandardSingleton.executed.get());
assertEquals(false, LazySingletonClass.executed.get());
}
public static void addInjector(String packageName) {
if (!logInjectors.contains(packageName)) {
Guice.createInjector(Stage.PRODUCTION, new NoraUiLoggingModule(packageName));
LOGGER.info("Created injector: {}", packageName);
} else {
if (LOGGER.isWarnEnabled()) {
LOGGER.warn("{} {} ", Messages.getMessage(TechnicalException.TECHNICAL_ERROR_MESSAGE),
String.format(Messages.getMessage(TECHNICAL_ERROR_MESSAGE_NORAUI_LOGGING_INJECTOR_ALREADY_EXISTS), packageName));
}
}
}
@Test
void runtimeConfigurationTest(@TempDir Path tmpArtifactDir) throws Exception {
int port = 0; // any port
// Use 'production' stage as it involves up-front error checking of the configured bindings
Injector injector = Guice.createInjector(Stage.PRODUCTION,
new FrameworkModule(tmpArtifactDir, port, emptyMap()));
// Create the runtime
ServiceRuntime runtime = injector.getInstance(ServiceRuntime.class);
try (TemporaryDb database = TemporaryDb.newInstance();
Cleaner cleaner = new Cleaner()) {
// Initialize it
runtime.initialize(mock(NodeProxy.class));
// Deploy the service to the runtime
runtime.deployArtifact(ARTIFACT_ID, ARTIFACT_FILENAME);
assertTrue(runtime.isArtifactDeployed(ARTIFACT_ID));
// Initialize and register a service instance
String name = "s1";
ServiceInstanceSpec instanceSpec = ServiceInstanceSpec.newInstance(name, 1, ARTIFACT_ID);
InstanceStatus instanceStatus = InstanceStatus.newBuilder().setSimple(Simple.ACTIVE).build();
Fork fork = database.createFork(cleaner);
BlockchainData blockchainData = BlockchainData.fromRawAccess(fork, name);
runtime.initiateAddingService(blockchainData, instanceSpec, new byte[0]);
runtime.updateInstanceStatus(instanceSpec, instanceStatus);
assertThat(runtime.findService(name)).isNotEmpty();
}
// Shutdown the runtime
runtime.shutdown();
}
@Test
void allAppropriateCreatorsAreLoadedInTheModule() {
List<String> expected = Stream.of(
FirefoxDriverCreator.class,
IeDriverCreator.class,
ChromeDriverCreator.class,
EdgeDriverCreator.class,
SafariDriverCreator.class,
RemoteDriverCreator.class)
.map(Class::getName)
.collect(toList());
List<String> actual =
Guice.createInjector(Stage.TOOL, new CoreModule()).getBindings().entrySet()
.stream()
.filter(
entry -> entry.getKey().getTypeLiteral().getRawType()
.equals(WebDriverCreator.class))
.map(Map.Entry::getValue)
.map(Objects::toString)
.map(s -> {
Matcher matcher =
Pattern.compile(".*target=.*type=(.*), annotation=\\[none].*").matcher(s);
matcher.find();
return matcher.group(1);
})
.collect(toList());
assertThat(actual).containsAll(expected);
}
public static void main(String[] args) {
try {
Bootstrapper.create(Guice.createInjector(Stage.DEVELOPMENT))
.getInstance(VocabularyInitializer.class).doMain(args);
} catch (BiomedicusException e) {
e.printStackTrace();
}
}
private Application biomedicus() {
Injector biomedicusInjector;
if (injector != null) {
biomedicusInjector = injector.createChildInjector(modules);
} else {
biomedicusInjector = Guice.createInjector(Stage.PRODUCTION, modules);
}
return biomedicusInjector.getInstance(Application.class);
}
private static Injector buildRestrictedInjector(Module module)
{
return Guice.createInjector(
Stage.PRODUCTION,
ImmutableList.of(module, (binder) -> {
binder.disableCircularProxies();
}));
}
@Test
public void testBindings() {
//given
Injector guice = Application.getInjector();
//when
Binding<Stage> stage = guice.getBinding(Stage.class);
Binding<Injector> injector = guice.getBinding(Injector.class);
Binding<Logger> logger = guice.getBinding(Logger.class);
Binding<Config> config = guice.getBinding(Config.class);
Binding<JobFactory> jobFactory = guice.getBinding(JobFactory.class);
Binding<Cache> cache = guice.getBinding(Cache.class);
Binding<TemplateEngine> templateEngine = guice.getBinding(TemplateEngine.class);
Binding<OncePerRequestFilter> mangooRequestFilter = guice.getBinding(OncePerRequestFilter.class);
Binding<MangooBootstrap> mangooBootstrap = guice.getBinding(MangooBootstrap.class);
//then
assertThat(stage.getKey().getTypeLiteral().getType().getTypeName(), equalTo("com.google.inject.Stage"));
assertThat(injector.getKey().getTypeLiteral().getType().getTypeName(), equalTo("com.google.inject.Injector"));
assertThat(logger.getKey().getTypeLiteral().getType().getTypeName(), equalTo("java.util.logging.Logger"));
assertThat(config.getKey().getTypeLiteral().getType().getTypeName(), equalTo("io.mangoo.core.Config"));
assertThat(jobFactory.getKey().getTypeLiteral().getType().getTypeName(), equalTo("org.quartz.spi.JobFactory"));
assertThat(cache.getKey().getTypeLiteral().getType().getTypeName(), equalTo("io.mangoo.cache.Cache"));
assertThat(templateEngine.getKey().getTypeLiteral().getType().getTypeName(), equalTo("io.mangoo.templating.TemplateEngine"));
assertThat(mangooRequestFilter.getKey().getTypeLiteral().getType().getTypeName(), equalTo("io.mangoo.interfaces.filters.OncePerRequestFilter"));
assertThat(mangooBootstrap.getKey().getTypeLiteral().getType().getTypeName(), equalTo("io.mangoo.interfaces.MangooBootstrap"));
}
@Override
public void initialize(Bootstrap<?> bootstrap) {
deModule = new DropwizardEnvironmentModule<>(type);
modules.add(new JerseyModule());
modules.add(deModule);
injector = Guice.createInjector(Stage.PRODUCTION, modules);
}
@Override
public void contextInitialized(ServletContextEvent sce) {
/*
* TODO switch to production
*/
logger.info("created injector");
injector = Guice.createInjector(Stage.DEVELOPMENT,
new DevelopersSharedModule(),
new DevelopersSharedServletModule(),
new DefaultServletModule());
super.contextInitialized(sce);
}
@Override
public String renderReport(final GuiceConfig config) {
// analyze modules
final List<ModuleDeclaration> moduleItems = filter(
GuiceModelParser.parse(injector, Elements.getElements(Stage.TOOL, modules)), config);
final Map<Key, BindingDeclaration> moduleBindings = GuiceModelUtils.index(moduleItems);
// don't show extensions if no guice module analysis actually performed
if (analysisEnabled) {
markExtensions(moduleBindings);
}
// analyze overrides
final List<ModuleDeclaration> overrideItems = filter(overridden.isEmpty()
? Collections.emptyList() : GuiceModelParser.parse(injector,
Elements.getElements(Stage.TOOL, overridden)), config);
final Map<Key, BindingDeclaration> overrideBindings = GuiceModelUtils.index(overrideItems);
markOverrides(moduleBindings, overrideBindings);
final StringBuilder res = new StringBuilder();
res.append(Reporter.NEWLINE).append(Reporter.NEWLINE);
// put all known bindings together for remaining reports
renderModules(res, moduleItems, moduleBindings);
renderOverrides(res, overrideItems, overrideBindings);
moduleBindings.putAll(overrideBindings);
renderJitBindings(res, moduleBindings, config, extensions);
renderBindingChains(res, moduleBindings);
return res.toString();
}
@Override
public void extensionBound(final Stage stage, final Class<?> type) {
if (stage != Stage.TOOL) {
// reporting (common for both registration types)
final boolean hkManaged = isJerseyExtension(type);
reporter.provider(type, hkManaged, false);
}
}
@Override
public <T> void manualBinding(final Binder binder, final Class<T> type, final Binding<T> binding) {
// we can only validate existing binding here (actually entire extension is pretty useless in case of manual
// binding)
final Class<? extends Annotation> scope = binding.acceptScopingVisitor(VISITOR);
// in production all services will work as eager singletons, for report (TOOL stage) consider also valid
Preconditions.checkArgument(scope.equals(EagerSingleton.class)
|| (!binder.currentStage().equals(Stage.DEVELOPMENT)
&& scope.equals(Singleton.class)),
// intentially no "at" before stacktrtace because idea may hide error in some cases
"Eager bean, declared manually is not marked .asEagerSingleton(): %s (%s)",
type.getName(), BindingUtils.getDeclarationSource(binding));
}
@Override
public void extensionBound(final Stage stage, final Class<?> type) {
if (stage != Stage.TOOL) {
// may be called multiple times if bindings report enabled, but log must be counted just once
prerender.add(String.format("%s", RenderUtils.renderClassLine(type)));
}
}
@Override
protected void configureServlets() {
// avoid registrations for guice reports (performing modules analysis and so calling this code many times)
if (currentStage() != Stage.TOOL) {
final GuiceFilter guiceFilter = new GuiceFilter();
environment.servlets().addFilter(GUICE_FILTER, guiceFilter)
.addMappingForUrlPatterns(dispatcherTypes, false, ROOT_PATH);
environment.admin().addFilter(GUICE_FILTER, new AdminGuiceFilter(guiceFilter))
.addMappingForUrlPatterns(dispatcherTypes, false, ROOT_PATH);
}
}
@Override
public Injector createInjector(final Stage stage, final Iterable<? extends Module> modules) {
final Module[] override = OVERRIDING_MODULES.get();
OVERRIDING_MODULES.remove();
TOO_LATE.set(true);
if (override != null) {
printOverridingModules(override);
}
return Guice.createInjector(stage, override == null ? modules
: Lists.newArrayList(Modules.override(modules).with(override)));
}