对于使用SpringBoot>=2.0.1将ZonedDateTime保存到MongoDB时发生CodecConfigurationException感兴趣的读者,本文将会是一篇不错的选择,并为您提供
对于使用Spring Boot> = 2.0.1将ZonedDateTime保存到MongoDB时发生CodecConfigurationException感兴趣的读者,本文将会是一篇不错的选择,并为您提供关于Azure Cosmos DB - 间歇性 MongoConnectionException / IOException / SocketException、Caused by: org.springframework.context.annotation.ConflictingBeanDefinitionException、com.google.inject.ConfigurationException的实例源码、ConfigurationErrorsException: Unrecognized configuration section system.data.的有用信息。
本文目录一览:- 使用Spring Boot> = 2.0.1将ZonedDateTime保存到MongoDB时发生CodecConfigurationException
- Azure Cosmos DB - 间歇性 MongoConnectionException / IOException / SocketException
- Caused by: org.springframework.context.annotation.ConflictingBeanDefinitionException
- com.google.inject.ConfigurationException的实例源码
- ConfigurationErrorsException: Unrecognized configuration section system.data.
使用Spring Boot> = 2.0.1将ZonedDateTime保存到MongoDB时发生CodecConfigurationException
通过对用于使用MongoDB访问数据的官方Spring
Boot指南进行了最小的修改,我能够重现我的问题,请参阅https://github.com/thokrae/spring-data-mongo-
zoneddatetime。
在将java.time.ZonedDateTime
字段添加到Customer类之后,从指南中运行示例代码失败,并出现CodecConfigurationException:
Customer.java:
public String lastName; public ZonedDateTime created; public Customer() {
输出:
...Caused by: org.bson.codecs.configuration.CodecConfigurationException`: Can''t find a codec for class java.time.ZonedDateTime.at org.bson.codecs.configuration.CodecCache.getOrThrow(CodecCache.java:46) ~[bson-3.6.4.jar:na]at org.bson.codecs.configuration.ProvidersCodecRegistry.get(ProvidersCodecRegistry.java:63) ~[bson-3.6.4.jar:na]at org.bson.codecs.configuration.ChildCodecRegistry.get(ChildCodecRegistry.java:51) ~[bson-3.6.4.jar:na]
这可以通过将pom.xml中的Spring Boot版本从2.0.5.RELEASE更改为2.0.1.RELEASE来解决:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.1.RELEASE</version> </parent>
现在,异常消失了,并将包括ZonedDateTime字段的Customer对象写入MongoDB。
我在spring-data-
mongodb项目中提交了一个错误(DATAMONGO-2106),但会了解是否不希望更改此行为,也不具有较高的优先级。
最好的解决方法是什么?当duckduckgoing为异常消息时,我找到了几种方法,如注册定制编解码器,定制转换器或使用Jackson JSR 310。我宁愿不向项目添加自定义代码来处理java.time包中的类。
答案1
小编典典像Oliver Drotbohm自己在DATAMONGO-2106中所说的那样,Spring Data MongoDB从未支持使用时区保留日期时间类型。
这些是已知的解决方法:
- 使用不带时区的日期时间类型,例如java.time.Instant。(通常建议仅在后端使用UTC,但是我不得不扩展采用不同方法的现有代码库。)
- 编写一个自定义转换器,并通过扩展AbstractMongoConfiguration对其进行注册。有关运行示例,请参见我的测试库中的分支转换器。
@Component@WritingConverterpublic class ZonedDateTimeToDocumentConverter implements Converter<ZonedDateTime, Document> { static final String DATE_TIME = "dateTime"; static final String ZONE = "zone"; @Override public Document convert(@Nullable ZonedDateTime zonedDateTime) { if (zonedDateTime == null) return null; Document document = new Document(); document.put(DATE_TIME, Date.from(zonedDateTime.toInstant())); document.put(ZONE, zonedDateTime.getZone().getId()); document.put("offset", zonedDateTime.getOffset().toString()); return document; }}@Component@ReadingConverterpublic class DocumentToZonedDateTimeConverter implements Converter<Document, ZonedDateTime> { @Override public ZonedDateTime convert(@Nullable Document document) { if (document == null) return null; Date dateTime = document.getDate(DATE_TIME); String zoneId = document.getString(ZONE); ZoneId zone = ZoneId.of(zoneId); return ZonedDateTime.ofInstant(dateTime.toInstant(), zone); }}@Configurationpublic class MongoConfiguration extends AbstractMongoConfiguration { @Value("${spring.data.mongodb.database}") private String database; @Value("${spring.data.mongodb.host}") private String host; @Value("${spring.data.mongodb.port}") private int port; @Override public MongoClient mongoClient() { return new MongoClient(host, port); } @Override protected String getDatabaseName() { return database; } @Bean public CustomConversions customConversions() { return new MongoCustomConversions(asList( new ZonedDateTimeToDocumentConverter(), new DocumentToZonedDateTimeConverter() )); }}
- 编写自定义编解码器。至少在理论上。使用Spring Boot 2.0.5时,我的编解码器测试分支无法解组数据,同时与Spring Boot 2.0.1正常工作。
public class ZonedDateTimeCodec implements Codec<ZonedDateTime> { public static final String DATE_TIME = "dateTime"; public static final String ZONE = "zone"; @Override public void encode(final BsonWriter writer, final ZonedDateTime value, final EncoderContext encoderContext) { writer.writeStartDocument(); writer.writeDateTime(DATE_TIME, value.toInstant().getEpochSecond() * 1_000); writer.writeString(ZONE, value.getZone().getId()); writer.writeEndDocument(); } @Override public ZonedDateTime decode(final BsonReader reader, final DecoderContext decoderContext) { reader.readStartDocument(); long epochSecond = reader.readDateTime(DATE_TIME); String zoneId = reader.readString(ZONE); reader.readEndDocument(); return ZonedDateTime.ofInstant(Instant.ofEpochSecond(epochSecond / 1_000), ZoneId.of(zoneId)); } @Override public Class<ZonedDateTime> getEncoderClass() { return ZonedDateTime.class; }}@Configurationpublic class MongoConfiguration extends AbstractMongoConfiguration { @Value("${spring.data.mongodb.database}") private String database; @Value("${spring.data.mongodb.host}") private String host; @Value("${spring.data.mongodb.port}") private int port; @Override public MongoClient mongoClient() { return new MongoClient(host + ":" + port, createOptions()); } private MongoClientOptions createOptions() { CodecProvider pojoCodecProvider = PojoCodecProvider.builder() .automatic(true) .build(); CodecRegistry registry = CodecRegistries.fromRegistries( createCustomCodecRegistry(), MongoClient.getDefaultCodecRegistry(), CodecRegistries.fromProviders(pojoCodecProvider) ); return MongoClientOptions.builder() .codecRegistry(registry) .build(); } private CodecRegistry createCustomCodecRegistry() { return CodecRegistries.fromCodecs( new ZonedDateTimeCodec() ); } @Override protected String getDatabaseName() { return database; }}
Azure Cosmos DB - 间歇性 MongoConnectionException / IOException / SocketException
如何解决Azure Cosmos DB - 间歇性 MongoConnectionException / IOException / SocketException?
我将 Azure Cosmos DB 4.0 与 MongoDB C# 驱动程序 2.10.4 结合使用。
大多数时候查询工作正常,但我遇到了这样的间歇性错误:
MongoDB.Driver.MongoConnectionException:向服务器发送消息时发生异常。 System.IO.IOException:无法将数据写入传输连接:远程主机强行关闭了现有连接。 System.Net.sockets.socketException: 一个现有的连接被远程主机强行关闭 在 System.Net.sockets.socket.BeginSend(... 在 System.Net.sockets.NetworkStream.BeginWrite --- 内部异常堆栈跟踪结束 --- 在 System.Net.sockets.NetworkStream.BeginWrite 在 System.Net.Security._SslStream.StartWriting 在 System.Net.Security._SslStream.ProcessWrite 在 System.Net.Security._SslStream.BeginWrite
发生该错误时,调用需要 10-25 秒才能失败。
我正在使用 @H_301_9@new MongoClient(MongoClientSettings.FromConnectionString(cnstr)) 构建 MongoClient,并且我使用的是带有这些参数 @H_301_9@?ssl=true&replicaset=globaldb&retrywrites=false 的连接字符串。
我尝试使用 @H_301_9@retryWrites=true(根据 Azure 支持建议),但这没有帮助。
我尝试了不同的设置,但都不起作用(@H_301_9@connect=direct、@H_301_9@maxIdleTimeMS=30000、@H_301_9@serverSelectionTimeout=5000ms、@H_301_9@socketTimeout=10000ms)。
导致这些异常的原因是什么?
解决方法
修复是设置/强制使用 TLS 1.2(基于 this Microsoft document):
//return new MongoClient(connectionString);
var settings = MongoClientSettings.FromConnectionString(connectionString);
settings.SslSettings = new SslSettings()
{
EnabledSslProtocols = System.Security.Authentication.SslProtocols.Tls12
};
return new MongoClient(settings);
看起来虽然我的连接字符串有 ssl=true
,但在某些服务器上还不够(错误是间歇性的)。 forcing TLS 1.2 通常可以修复相同的潜在错误,因此我认为在 Mongo 中它可能是相同的问题 - 它确实解决了问题。
Caused by: org.springframework.context.annotation.ConflictingBeanDefinitionException
org.springframework.context.annotation.ConflictingBeanDefinitionException: Annotation-specified bean name ''BusinessAccountController'' for bean class [com.hs.BusinessAccountController] conflicts with existing, non-compatible bean definition of same name and class [com.hs.BusinessAccountController]
at org.springframework.context.annotation.ClassPathBeanDefinitionScanner.checkCandidate(ClassPathBeanDefinitionScanner.java:314)
at org.mybatis.spring.mapper.ClassPathMapperScanner.checkCandidate(ClassPathMapperScanner.java:223)
at org.springframework.context.annotation.ClassPathBeanDefinitionScanner.doScan(ClassPathBeanDefinitionScanner.java:253)
at org.mybatis.spring.mapper.ClassPathMapperScanner.doScan(ClassPathMapperScanner.java:155)
at org.springframework.context.annotation.ClassPathBeanDefinitionScanner.scan(ClassPathBeanDefinitionScanner.java:220)
问题的根源是出现bean名称重复
原因:
1.两个bean名称重复,spring扫描无法创建bean对象(有时候会与引入的第三方的jar包中的bean名称重复);
2.target中有缓存导致,Maven项目clean下再编译
com.google.inject.ConfigurationException的实例源码
@Test public void testNotExposed() { final Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { DuplexBinder.create(this.binder()).install(new DuplexModule() { @Override protected void configure() { this.bind(Thing.class).annotatedWith(Names.named("r0")).toInstance(new Thing("r0")); } }); } }); try { injector.getInstance(ShouldNotWork.class); } catch(final ConfigurationException expected) { final String message = expected.getMessage(); if(message.contains("It was already configured on one or more child injectors or private modules") && message.contains("If it was in a PrivateModule,did you forget to expose the binding?")) { return; } } fail("should not be exposed"); }
private void analyzeImplementation(final TypeLiteral<?> type,boolean ignoreConstructor) { if( !scannedTypes.contains(type) ) { try { if( (type.getRawType().getModifiers() & (Modifier.INTERFACE | Modifier.ABSTRACT)) == 0 ) { analyzeInjectionPoints(InjectionPoint.forInstanceMethodsAndFields(type)); if( !ignoreConstructor ) { analyzeDependencies(InjectionPoint.forConstructorOf(type).getDependencies()); } } } catch( ConfigurationException ce ) { errors.merge(ce.getErrorMessages()); } scannedTypes.add(type); } }
@Test public void testLoadMap() throws Exception { Map<String,TestInterface> services = target.loadMap(TestInterface.class); assertTrue(services.get("TestImpl1") instanceof TestInterface.TestImpl1); assertTrue(services.get("TestImpl3") instanceof TestInterface.TestImpl3); assertEquals(services.size(),2,services.toString()); for (TestInterface s : services.values()) { assertNotNull(s.getInjector()); assertNotNull(s.getInjector().getInstance(ImmutableConfiguration.class)); try { s.getInjector().getInstance(ServiceFactory.class); fail(); } catch (ConfigurationException e) { // Success } } }
/** * This method produces value for the field. It constructs the context for the creation out of * paren't context and the field's own frame info. */ @Override public Optional<Object> provideValue(Object pageObject,Field field,PageObjectContext context) { By selector = PageObjectProviderHelper.getSelectorFromPageObject(field); ElementLocatorFactory elementLocatorFactory = new nestedSelectorScopedLocatorFactory(webDriver,selector,context.getElementLocatorFactory(),AnnotationsHelper.isGlobal(field)); final FramePath framePath = frameMap.get(pageObject); contextStack.push(new PageObjectContext(elementLocatorFactory,framePath)); Object scopedPageObject = null; try { scopedPageObject = injector.getInstance(field.getType()); } catch (Exception e) { if (e instanceof ConfigurationException) { ConfigurationException ce = (ConfigurationException) e; throw new BobcatRuntimeException( "Configuration exception: " + ce.getErrorMessages().toString(),e); } throw new BobcatRuntimeException(e.getMessage(),e); } finally { contextStack.pop(); } return Optional.ofNullable(scopedPageObject); }
/** * This method produces value for the field. It constructs the context for the creation out of * parent's context and the field's own frame info. */ @Override public Optional<Object> provideValue(Object pageObject,PageObjectContext context) { final ElementLocatorFactory elementLocatorFactory = new ScopedElementLocatorFactory(webDriver,field); final FramePath framePath = frameMap.get(pageObject); contextStack.push(new PageObjectContext(elementLocatorFactory,e); } finally { contextStack.pop(); } return Optional.ofNullable(scopedPageObject); }
/** * @param args the arguments * @param parser the command line parser containing usage information * @return a child Command for the given args,or <code>null</code> if not found */ protected Command getChildAction(List<String> args,CmdLineParser parser) { final String commandName = args.get(0); // find implementation final Class<? extends Command> commandClass = commandMap.get(commandName); if (null != commandClass) { try { final Command command = InjectionUtil.getInjector().getInstance(commandClass); command.setParent(this); command.setCommandName(commandName); return command; } catch (ProvisionException | ConfigurationException e) { throw new CommandException(String.format("Error getting child command for args: %s",args),e); } } return null; }
@Override public Object resolve(Injectee injectee,ServiceHandle<?> serviceHandle) { if (injectee.getrequiredType() instanceof Class) { TypeLiteral<?> typeLiteral = TypeLiteral.get(injectee.getrequiredType()); Errors errors = new Errors(injectee.getParent()); Key<?> key; try { key = Annotations.getKey(typeLiteral,(Member) injectee.getParent(),injectee.getParent().getDeclaredAnnotations(),errors); } catch (ErrorsException e) { errors.merge(e.getErrors()); throw new ConfigurationException(errors.getMessages()); } return injector.getInstance(key); } throw new IllegalStateException("Can't process injection point: " + injectee.getrequiredType()); }
/** * Finds the {@link IResourceServiceProvider} for a language by given its id. * * @param languageId * the language id (grammar name) * @return the {@link IResourceServiceProvider} for the given language id */ public IResourceServiceProvider getResourceServiceProviderById(final String languageId) { ImmutableMap<Map<String,Object>,? extends Function<String,IResourceServiceProvider>> resourceProvidersMap = getProviderMaps(); for (Map.Entry<Map<String,IResourceServiceProvider>> mapEntry : resourceProvidersMap.entrySet()) { Map<String,Object> map = mapEntry.getKey(); for (Map.Entry<String,Object> entry : map.entrySet()) { try { IResourceServiceProvider resourceServiceProvider = mapEntry.getValue().apply(entry.getKey()); if (resourceServiceProvider == null) { continue; } IGrammaraccess grammaraccess = resourceServiceProvider.get(IGrammaraccess.class); if (grammaraccess != null && grammaraccess.getGrammar().getName().equals(languageId)) { return resourceServiceProvider; } // CHECKSTYLE:OFF } catch (ConfigurationException ex) { // CHECKSTYLE:ON // ignore } } } return null; }
/** * Gets the all languages available in the workbench. * * @return set of all languages */ public Set<String> getAllLanguages() { Set<String> languages = new HashSet<String>(); for (String extension : Registry.INSTANCE.getExtensionToFactoryMap().keySet()) { final URI dummyUri = URI.createURI("foo:/foo." + extension); IResourceServiceProvider resourceServiceProvider = Registry.INSTANCE.getResourceServiceProvider(dummyUri); // By checking that description manager is AbstractCachingResourceDescriptionManager we exclude technical languages of the framework if (resourceServiceProvider != null && resourceServiceProvider.getResourceDescriptionManager() instanceof AbstractCachingResourceDescriptionManager) { try { IGrammaraccess grammaraccess = resourceServiceProvider.get(IGrammaraccess.class); if (grammaraccess != null && grammaraccess.getGrammar() != null) { languages.add(grammaraccess.getGrammar().getName()); } } catch (ConfigurationException e) { // Will happen if no binding for IGrammaraccess was present. } } } return languages; }
@Override public Object resolve(Injectee injectee,errors); } catch (ErrorsException e) { errors.merge(e.getErrors()); throw new ConfigurationException(errors.getMessages()); } return injector.getInstance(key); } throw new IllegalStateException("Can't process injection point: " + injectee.getrequiredType()); }
private Optional<String> getCurrentTestLogFileName() { Optional<TestContext> testContext = testContextIfSet(); try { String testName = "SUITE"; if (testContext.isPresent()) { Optional<TestMetadata> testMetadata = testContext.get().getoptionalDependency(TestMetadata.class); if (testMetadata.isPresent()) { testName = testMetadata.get().testName; } } return Optional.of(logsDirectory + "/" + testName); } catch (ConfigurationException e) { System.err.append("Could not load TestMetadata from guice context"); return Optional.empty(); } }
public static void main(String... args) { WSFRealtimeMain m = new WSFRealtimeMain(); ArgumentParser parser = ArgumentParsers.newArgumentParser("wsf-gtfsrealtime"); parser.description("Produces a GTFS-realtime Feed from the Washington State Ferries API"); parser.addArgument("--" + ARG_CONfig_FILE).type(File.class).help("configuration file path"); Namespace parsedArgs; try { parsedArgs = parser.parseArgs(args); File configFile = parsedArgs.get(ARG_CONfig_FILE); m.run(configFile); } catch (CreationException | ConfigurationException | ProvisionException e) { _log.error("Error in startup:",e); System.exit(-1); } catch (ArgumentParserException ex) { parser.handleError(ex); } }
private void createBindingsForFactories(GinjectorBindings bindings) { for (final FactoryModule<?> factoryModule : bindings.getFactoryModules()) { FactoryBinding binding; try { binding = bindingFactory.getFactoryBinding( factoryModule.getBindings(),factoryModule.getFactoryType(),Context.forText(factoryModule.getSource())); } catch (ConfigurationException e) { errorManager.logError("Factory %s Could not be created",e,factoryModule.getFactoryType()); continue; } bindings.addBinding(factoryModule.getFactoryType(),binding); } }
private static TestWrapper buildTestWrapperInstance(Injector injector) { TestWrapper result = NoOpTestScopeListener.NO_OP_INSTANCE; try { boolean hasTestScopeListenerBinding = hasTestScopeListenerBinding(injector); boolean hasDeprecatedTestScopeListenerBinding = hasDeprecatedTestScopeListenerBinding(injector); if (hasTestScopeListenerBinding && hasDeprecatedTestScopeListenerBinding) { throw new RuntimeException( "Your GuiceBerry Env has bindings for both the new TestScopeListener and the deprecated one. Please fix."); } else if (hasTestScopeListenerBinding) { result = injector.getInstance(TestWrapper.class); } else if (hasDeprecatedTestScopeListenerBinding) { result = adapt( injector.getInstance(com.google.inject.testing.guiceBerry.TestScopeListener.class),injector.getInstance(TearDownAccepter.class)); } } catch (ConfigurationException e) { String msg = String.format("Error while creating a TestWrapper: '%s'.",e.getMessage()); throw new RuntimeException(msg,e); } return result; }
/** * This test makes sure that if the test has a missing binding,GuiceBerry * will fail before it runs the {@link GuiceBerryEnvmain#run()} method. */ @Test public void testFailsInjectionBeforeRunningGuiceBerryEnvmain_MissingTestBinding() { GuiceBerryEnvSelector guiceBerryEnvSelector = DefaultEnvSelector.of(MyGuiceBerryEnvWithGuiceBerryEnvmainThatThrows.class); TestDescription testDescription = new TestDescription(new ClassWithUnsatisfiedDependency(),"bogus test case"); GuiceBerryUniverse.TestCaseScaffolding testCaseScaffolding = new GuiceBerryUniverse.TestCaseScaffolding(testDescription,guiceBerryEnvSelector,universe); try { testCaseScaffolding.runBeforetest(); Assert.fail("The test has an unsatisfied injection,and the GuiceBerryEnvmain " + "throws an Exception. Either of these reasons should have prevented the " + "test from having gotten here."); } catch (MyGuiceBerryEnvWithGuiceBerryEnvmainThatThrows.GuiceBerryEnvmainWasExecutedException toThrow) { throw toThrow; } catch (RuntimeException maybeExpected) { Assert.assertEquals(ConfigurationException.class,maybeExpected.getCause().getClass()); } testCaseScaffolding.runAftertest(); }
public void testGbeThatHasMissingBindingsThrowsException() { try { TestWithGbeThatHasMissingBindings test = TestWithGbeThatHasMissingBindings.createInstance(); instance().doSetUp(test); fail(); } catch (RuntimeException expectedActualException) { //Todo: we should assert expected's cause is ConfigurationException,but //that exception is private Throwable actualCause = expectedActualException.getCause(); assertEquals(ConfigurationException.class,actualCause.getClass()); assertEquals(String.format( "Binding error in the GuiceBerry Env '%s': '%s'.",GuiceBerryEnvWithoutBindingsForFooOrBar.GUICE_Berry_ENV_WITHOUT_BINDINGS_FOR_FOO_OR_BAR,actualCause.getMessage()),expectedActualException.getMessage()); String configurationExceptionMeat = String.format( "No implementation for %s was bound.",BarService.class.getName()); assertTrue(actualCause.getMessage().contains(configurationExceptionMeat)); } }
private <E> List<E> provide(TypeLiteral<Set<E>> type) { List<E> collection; try { Set<E> retrieved = injector.getInstance(Key.get(type)); collection = retrieved.stream().filter(Objects::nonNull).collect(toList()); if (collection.isEmpty()) { throw new ConfigurationException(new ArrayList<>()); } } catch (ConfigurationException ce) { log.info(() -> "There is no registered instance of the type: "); collection = new ArrayList<>(); } return collection; }
public synchronized void shutdown() { if (plugins != null) { Arrays.stream(plugins).forEach(plugin -> plugin.destroy()); } onShutdown.forEach(Runnable::run); if (injector != null) { // shutdown the database connection pool try { DatabaseConnection connection = injector.getInstance(DatabaseConnection.class); if (connection != null) connection.close(); } catch (ConfigurationException ignore) { } catch (Exception e) { e.printstacktrace(); } // signal the framework that we are closing down FrameworkEngine engine = injector.getInstance(FrameworkEngine.class); engine.onFrameworkShutdown(); injector = null; engine = null; } }
private void addMessageIfinformative(LinkedList<String> messages,Throwable cause) { if (cause instanceof ProvisionException) { // This technical exception is hidden. Only its causes should be shown. return; } if (cause instanceof ConfigurationException) { // A missing setting in settings.properties can cause this exception. ConfigurationException configurationException = (ConfigurationException) cause; addClearifiedErrorMessages(messages,configurationException.getErrorMessages()); return; } if (cause instanceof CreationException) { // A missing setting in settings.properties can cause this exception. CreationException creationException = (CreationException) cause; addClearifiedErrorMessages(messages,creationException.getErrorMessages()); return; } messages.add(cause.getMessage()); }
@Override public <C extends IRequestablePage> C newPage(final Class<C> pageClass) { LOG.debug("Creating new {} page without parameters",pageClass.getName()); if (!Application.get().getSecuritySettings().getAuthorizationStrategy().isInstantiationAuthorized(pageClass)) { throw new RestartResponseAtInterceptPageException(wicketSettings.getLoginPageClass()); } try { final C pageInstance = injector.createChildInjector(new AbstractModule() { @Override protected void configure() { bind(PageParameters.class).toInstance(new PageParameters()); } }).getInstance(pageClass); return pageInstance; } catch(final ConfigurationException e) { LOG.debug("Could not create page {} through Guice,trying manually: {}",pageClass,e.getMessage()); return createOrThrow(pageClass,null); } }
@Override public <C extends IRequestablePage> C newPage(final Class<C> pageClass,final PageParameters parameters) { LOG.debug("Creating new {} page with parameters: {}",pageClass.getName(),parameters); try { final C pageInstance = injector.createChildInjector(new AbstractModule() { @Override protected void configure() { bind(PageParameters.class).toInstance(parameters); } }).getInstance(pageClass); return pageInstance; } catch(final ConfigurationException e) { LOG.debug("Could not create page {} through Guice,e.getMessage()); return createOrThrow(pageClass,parameters); } }
public void testBindingSuperTypeAccessSubType() { final Integer testValue = 1024; Object instance = new Object() { @Bind(to = Number.class) private Integer anInt = testValue; }; BoundFieldModule module = BoundFieldModule.of(instance); Injector injector = Guice.createInjector(module); try { injector.getInstance(Integer.class); fail(); } catch (ConfigurationException e) { assertContains(e.getMessage(),"Could not find a suitable constructor in java.lang.Integer"); } }
public void testProviderSubclassesDoNotBindParameterizedType() { final Integer testValue = 1024; Object instance = new Object() { @Bind private IntegerProvider anIntProvider = new IntegerProvider(testValue); }; BoundFieldModule module = BoundFieldModule.of(instance); Injector injector = Guice.createInjector(module); try { injector.getInstance(Integer.class); fail(); } catch (ConfigurationException e) { assertContains(e.getMessage(),"Could not find a suitable constructor in java.lang.Integer."); } }
/** * Returns all static method and field injection points on {@code type}. * * @return a possibly empty set of injection points. The set has a specified iteration order. All * fields are returned and then all methods. Within the fields,supertype fields are returned * before subtype fields. Similarly,supertype methods are returned before subtype methods. * @throws ConfigurationException if there is a malformed injection point on {@code type},such as * a field with multiple binding annotations. The exception's {@link * ConfigurationException#getPartialValue() partial value} is a {@code Set<InjectionPoint>} of * the valid injection points. */ public static Set<InjectionPoint> forStaticmethodsAndFields(TypeLiteral<?> type) { Errors errors = new Errors(); Set<InjectionPoint> result; if (type.getRawType().isInterface()) { errors.staticInjectionOnInterface(type.getRawType()); result = null; } else { result = getInjectionPoints(type,true,errors); } if (errors.hasErrors()) { throw new ConfigurationException(errors.getMessages()).withPartialValue(result); } return result; }
/** Returns a set of dependencies that can be iterated over to clean up stray JIT bindings. */ Set<Dependency<?>> getInternalDependencies() { ImmutableSet.Builder<InjectionPoint> builder = ImmutableSet.builder(); if (factory.constructorInjector == null) { builder.add(constructorInjectionPoint); // If the below throws,it's OK -- we just ignore those dependencies,because no one // Could have used them anyway. try { builder.addAll( InjectionPoint.forInstanceMethodsAndFields( constructorInjectionPoint.getDeclaringType())); } catch (ConfigurationException ignored) { } } else { builder.add(getConstructor()).addAll(getInjectableMembers()); } return Dependency.forInjectionPoints(builder.build()); }
@Override public void toInstance(T instance) { checkNottargetted(); // lookup the injection points,adding any errors to the binder's errors list Set<InjectionPoint> injectionPoints; if (instance != null) { try { injectionPoints = InjectionPoint.forInstanceMethodsAndFields(instance.getClass()); } catch (ConfigurationException e) { copyErrorsToBinder(e); injectionPoints = e.getPartialValue(); } } else { binder.addError(BINDING_TO_NULL); injectionPoints = ImmutableSet.of(); } BindingImpl<T> base = getBinding(); setBinding( new InstanceBindingImpl<T>( base.getSource(),base.getKey(),scoping.EAGER_SINGLetoN,injectionPoints,instance)); }
@Override public BindingBuilder<T> toProvider(javax.inject.Provider<? extends T> provider) { checkNotNull(provider,"provider"); checkNottargetted(); // lookup the injection points,adding any errors to the binder's errors list Set<InjectionPoint> injectionPoints; try { injectionPoints = InjectionPoint.forInstanceMethodsAndFields(provider.getClass()); } catch (ConfigurationException e) { copyErrorsToBinder(e); injectionPoints = e.getPartialValue(); } BindingImpl<T> base = getBinding(); setBinding( new ProviderInstanceBindingImpl<T>( base.getSource(),base.getscoping(),provider)); return this; }
void validate() { Errors errorsForMember = errors.withSource(source); Set<InjectionPoint> injectionPoints; try { injectionPoints = request.getInjectionPoints(); } catch (ConfigurationException e) { errorsForMember.merge(e.getErrorMessages()); injectionPoints = e.getPartialValue(); } if (injectionPoints != null) { memberInjectors = injector.membersInjectorStore.getInjectors(injectionPoints,errorsForMember); } else { memberInjectors = ImmutableList.of(); } errors.merge(errorsForMember); }
/** * Find and invoke the relevant {@link SpecificationConverter} for the given specification to * convert it into an object of type {@link T}. * * @param specification the specification to convert. * @param context the translation context. * @param <S> the type of the specification to convert. * @return the converted target object representing the given specification. */ protected <S extends Specification<?>> T convert(S specification,C context) { if (specification instanceof SubstitutableSpecification) { return convert(((SubstitutableSpecification<?>) specification).getSubstitute(),context); } else { SpecificationConverter<S,C,T> converter; Class<? extends Specification> specificationClass = specification.getClass(); try { converter = injector.getInstance(buildKey(specificationClass)); } catch (ConfigurationException e) { throw BusinessException.wrap(e,BusinessErrorCode.NO_CONVERTER_FOUND) .put("contextClass",contextClass) .put("targetClass",targetClass) .put("specificationClass",specificationClass); } return converter.convert(specification,context,this); } }
public void testProviderSubclassesDoNotBindParameterizedType() { final Integer testValue = 1024; Object instance = new Object() { @Bind private IntegerProvider anIntProvider = new IntegerProvider(testValue); }; BoundFieldModule module = BoundFieldModule.of(instance); Injector injector = Guice.createInjector(module); try { injector.getInstance(Integer.class); fail(); } catch (ConfigurationException e) { assertContains(e.getMessage(),"Could not find a suitable constructor in java.lang.Integer."); } }
/** * At injector-creation time,we initialize the invocation handler. At this time we make sure * all factory methods will be able to build the target types. */ @Inject @Toolable void initialize(Injector injector) { if (this.injector != null) { throw new ConfigurationException(ImmutableList.of(new Message(FactoryProvider2.class,"Factories.create() factories may only be used in one Injector!"))); } this.injector = injector; for (Map.Entry<Method,AssistData> entry : assistDataByMethod.entrySet()) { Method method = entry.getKey(); AssistData data = entry.getValue(); Object[] args; if(!data.optimized) { args = new Object[method.getParameterTypes().length]; Arrays.fill(args,"dummy object for validating Factories"); } else { args = null; // won't be used -- instead will bind to data.providers. } getBindingFromNewInjector(method,args,data); // throws if the binding isn't properly configured } }
/** * Returns all static method and field injection points on {@code type}. * * @return a possibly empty set of injection points. The set has a specified iteration order. All * fields are returned and then all methods. Within the fields,supertype fields are returned * before subtype fields. Similarly,such as * a field with multiple binding annotations. The exception's {@link * ConfigurationException#getPartialValue() partial value} is a {@code Set<InjectionPoint>} * of the valid injection points. */ public static Set<InjectionPoint> forStaticmethodsAndFields(TypeLiteral<?> type) { Errors errors = new Errors(); Set<InjectionPoint> result; if (type.getRawType().isInterface()) { errors.staticInjectionOnInterface(type.getRawType()); result = null; } else { result = getInjectionPoints(type,errors); } if (errors.hasErrors()) { throw new ConfigurationException(errors.getMessages()).withPartialValue(result); } return result; }
/** Returns a set of dependencies that can be iterated over to clean up stray JIT bindings. */ Set<Dependency<?>> getInternalDependencies() { ImmutableSet.Builder<InjectionPoint> builder = ImmutableSet.builder(); if(factory.constructorInjector == null) { builder.add(constructorInjectionPoint); // If the below throws,because no one // Could have used them anyway. try { builder.addAll(InjectionPoint.forInstanceMethodsAndFields(constructorInjectionPoint.getDeclaringType())); } catch(ConfigurationException ignored) {} } else { builder.add(getConstructor()) .addAll(getInjectableMembers()); } return Dependency.forInjectionPoints(builder.build()); }
public void toInstance(T instance) { checkNottargetted(); // lookup the injection points,adding any errors to the binder's errors list Set<InjectionPoint> injectionPoints; if (instance != null) { try { injectionPoints = InjectionPoint.forInstanceMethodsAndFields(instance.getClass()); } catch (ConfigurationException e) { copyErrorsToBinder(e); injectionPoints = e.getPartialValue(); } } else { binder.addError(BINDING_TO_NULL); injectionPoints = ImmutableSet.of(); } BindingImpl<T> base = getBinding(); setBinding(new InstanceBindingImpl<T>( base.getSource(),instance)); }
public BindingBuilder<T> toProvider(javax.inject.Provider<? extends T> provider) { checkNotNull(provider,adding any errors to the binder's errors list Set<InjectionPoint> injectionPoints; try { injectionPoints = InjectionPoint.forInstanceMethodsAndFields(provider.getClass()); } catch (ConfigurationException e) { copyErrorsToBinder(e); injectionPoints = e.getPartialValue(); } BindingImpl<T> base = getBinding(); setBinding(new ProviderInstanceBindingImpl<T>( base.getSource(),provider)); return this; }
/** * Returns an type that's appropriate for use in a key. * * <p>If the raw type of {@code typeLiteral} is a {@code javax.inject.Provider},this returns a * {@code com.google.inject.Provider} with the same type parameters. * * <p>If the type is a primitive,the corresponding wrapper type will be returned. * * @throws ConfigurationException if {@code type} contains a type variable */ public static <T> TypeLiteral<T> canonicalizeforKey(TypeLiteral<T> typeLiteral) { Type type = typeLiteral.getType(); if (!isFullySpecified(type)) { Errors errors = new Errors().keyNotFullySpecified(typeLiteral); throw new ConfigurationException(errors.getMessages()); } if (typeLiteral.getRawType() == javax.inject.Provider.class) { ParameterizedType parameterizedType = (ParameterizedType) type; // the following casts are generally unsafe,but com.google.inject.Provider extends // javax.inject.Provider and is covariant @SuppressWarnings("unchecked") TypeLiteral<T> guiceProviderType = (TypeLiteral<T>) TypeLiteral.get( Types.providerOf(parameterizedType.getActualTypeArguments()[0])); return guiceProviderType; } @SuppressWarnings("unchecked") TypeLiteral<T> wrappedPrimitives = (TypeLiteral<T>) PRIMITIVE_TO_WRAPPER.get(typeLiteral); return wrappedPrimitives != null ? wrappedPrimitives : typeLiteral; }
void validate() { Errors errorsForMember = errors.withSource(source); Set<InjectionPoint> injectionPoints; try { injectionPoints = request.getInjectionPoints(); } catch (ConfigurationException e) { errorsForMember.merge(e.getErrorMessages()); injectionPoints = e.getPartialValue(); } if (injectionPoints != null) { memberInjectors = injector.membersInjectorStore.getInjectors( injectionPoints,errorsForMember); } else { memberInjectors = ImmutableList.of(); } errors.merge(errorsForMember); }
@SuppressWarnings("rawtypes") @Test public void oneCache() throws Exception { Config conf = ConfigFactory.empty() .withValue("caffeine.cache",ConfigValueFactory.fromAnyRef("")); new MockUnit(Env.class) .run(unit -> { Injector injector = Guice.createInjector(binder -> { new caffeineCache() { }.configure(unit.get(Env.class),conf,binder); }); injector.getInstance(RequireCache.class); try { injector.getInstance(caffeineSessionStore.class); fail("No session found"); } catch (ConfigurationException ex) { // OK } }); }
@SuppressWarnings("rawtypes") @Test public void cacheWithObjectSpec() throws Exception { Config conf = ConfigFactory.empty() .withValue("caffeine.cache.maximumSize",ConfigValueFactory.fromAnyRef(10)); new MockUnit(Env.class) .run(unit -> { Injector injector = Guice.createInjector(binder -> { new caffeineCache() { }.configure(unit.get(Env.class),binder); }); injector.getInstance(RequireCache.class); try { injector.getInstance(caffeineSessionStore.class); fail("No session found"); } catch (ConfigurationException ex) { // OK } }); }
@SuppressWarnings("rawtypes") @Test public void oneCache() throws Exception { Config conf = ConfigFactory.empty() .withValue("guava.cache",ConfigValueFactory.fromAnyRef("")); new MockUnit(Env.class) .run(unit -> { Injector injector = Guice.createInjector(binder -> { new GuavaCache() { }.configure(unit.get(Env.class),binder); }); injector.getInstance(RequireCache.class); try { injector.getInstance(GuavaSessionStore.class); fail("No session found"); } catch (ConfigurationException ex) { // OK } }); }
ConfigurationErrorsException: Unrecognized configuration section system.data.
报错
ConfigurationErrorsException: Unrecognized configuration section system.data. (C:\Users\luren\Source\Repos\StaffingSystem\StaffingSystem\bin\Debug\netcoreapp2.0\StaffingSystem.dll.config line 4)
一看就知道是 StaffingSystem.dll.config 的问题打开后发现长这样
其实我也不确定这些配置到底是什么问题然后我就去比对了其他的同样引用了 mysql.data 的项目发现
纳尼 啥都没有 ? 如上更改之后发现就解决问题了
那好吧。。可能是多余的配置导致的冲突
我们今天的关于使用Spring Boot> = 2.0.1将ZonedDateTime保存到MongoDB时发生CodecConfigurationException的分享就到这里,谢谢您的阅读,如果想了解更多关于Azure Cosmos DB - 间歇性 MongoConnectionException / IOException / SocketException、Caused by: org.springframework.context.annotation.ConflictingBeanDefinitionException、com.google.inject.ConfigurationException的实例源码、ConfigurationErrorsException: Unrecognized configuration section system.data.的相关信息,可以在本站进行搜索。
本文标签: