idea报错-java.lang.IllegalStateException:(数组Arrays.asList())

本文主要探讨了在使用MyBatis进行批量下架操作时遇到的数据库更新错误,原因是基本数据类型的数组无法直接应用于`Arrays.asList()`。解决办法是将参数类型从`long[]`改为`Long[]`,以匹配Java泛型的要求。通过这个修改,避免了TypeHandler为null的问题,确保了批量下架操作的正确执行。
### Error updating database.  Cause: java.lang.IllegalStateException: Type handler was null on parameter mapping for property '__frch_listItem_2'. It was either not specified and/or could not be found for the javaType ([J) : jdbcType (null) combination.
### Cause: java.lang.IllegalStateException: Type handler was null on parameter mapping for property '__frch_listItem_2'. It was either not specified and/or could not be found for the javaType ([J) : jdbcType (null) combination.] with root cause

java.lang.IllegalStateException: Type handler was null on parameter mapping for property '__frch_listItem_2'. It was either not specified and/or could not be found for the javaType ([J) : jdbcType (null) combination.
	at org.apache.ibatis.mapping.ParameterMapping$Builder.validate(ParameterMapping.java:119) ~[mybatis-3.4.6.jar:3.4.6]
	at org.apache.ibatis.mapping.ParameterMapping$Builder.build(ParameterMapping.java:104) ~[mybatis-3.4.6.jar:3.4.6]

代码:

/**
 *  批量下架
 * @param ids
 * @return
 */
@PutMapping("/pull/many")
public Result pullMany(@RequestBody long[] ids){
    int count = spuService.pullMany(ids);
    return new Result(true,StatusCode.OK,count+"款商品下架成功");
}


/**
 * 批量下架
 * @param ids
 * @return
 */
int pullMany(long[] ids);


/**
 * 批量下架
 * @param ids 需要下架的商品ID集合
 * @return
 */
@Override
public int pullMany(long[] ids) {
    //is_marketable是否上架,0已下架,1已上架
    //is_delete是否删除,0:未删除,1:已删除
    //status审核状态,0:未审核,1:已审核,2:审核不通过
    //批量上架 update tb_spu set is_marketable=1 where id in(ids)and is_delete=0 and is_marketable=0 and status=1
    //批量下架 update tb_spu set is_marketable=0 where id in(ids) and is_delete=0 and is_marketable=1 and status=1

    Spu spu=new Spu();
    spu.setIsMarketable("0");//下架
    Example example=new Example(Spu.class);
    Example.Criteria criteria = example.createCriteria();
    criteria.andIn("id", Arrays.asList(ids));//id
    //上架状态
    criteria.andEqualTo("isMarketable","1");
    //审核通过的
    criteria.andEqualTo("status","1");
    //非删除的
    criteria.andEqualTo("isDelete","0");
    return spuMapper.updateByExampleSelective(spu, example);
}

List<>集合中只能放引用类型,Arrays.asList()不能用于基本数据类型,适用于对象型数据的数组(String、Integer...)

程序运行的结果并是不是我们想要的5,而是1,这是因为asList方法接受的参数是一个可变长度的泛型

而java的8中基本数据类型是不能被泛型化的,其相应的包装类是可以被泛型化的,只有Object及

其子类才可以泛型化。数组是可以被泛型化的,所以此demo输出结果是1,而不是5。

要想输出是5,只需要将int改为Integer

换成Long[] ids即可

/**
 *  批量下架
 * @param ids
 * @return
 */
@PutMapping("/pull/many")
public Result pullMany(@RequestBody long[] ids){
    int count = spuService.pullMany(ids);
    return new Result(true,StatusCode.OK,count+"款商品下架成功");
}


/**
 * 批量下架
 * @param ids
 * @return
 */
int pullMany(long[] ids);


/**
 * 批量下架
 * @param ids 需要下架的商品ID集合
 * @return
 */
@Override
public int pullMany(Long[] ids) {
    //is_marketable是否上架,0已下架,1已上架
    //is_delete是否删除,0:未删除,1:已删除
    //status审核状态,0:未审核,1:已审核,2:审核不通过
    //批量上架 update tb_spu set is_marketable=1 where id in(ids)and is_delete=0 and is_marketable=0 and status=1
    //批量下架 update tb_spu set is_marketable=0 where id in(ids) and is_delete=0 and is_marketable=1 and status=1

    Spu spu=new Spu();
    spu.setIsMarketable("0");//下架
    Example example=new Example(Spu.class);
    Example.Criteria criteria = example.createCriteria();
    criteria.andIn("id", Arrays.asList(ids));//id
    //上架状态
    criteria.andEqualTo("isMarketable","1");
    //审核通过的
    criteria.andEqualTo("status","1");
    //非删除的
    criteria.andEqualTo("isDelete","0");
    return spuMapper.updateByExampleSelective(spu, example);
}

OpenJDK 64-Bit Server VM warning: Sharing is only supported for boot loader classes because bootstrap classpath has been appended 2025-09-24 16:29:38.924 [ConsoleDiscoveryClient-InstanceManager-1] [ERROR] [InstanceCacheManager.java:188] Refresh console instance cache failed java.lang.IllegalStateException: Console client have not found! at com.huawei.foundation.commons.console.client.ConsoleClient.getClient(ConsoleClient.java:145) at com.huawei.cube.rt.discovery.console.InstanceCacheManager.refreshInstanceCache(InstanceCacheManager.java:173) at com.huawei.cube.rt.discovery.console.InstanceCacheManager.lambda$execute$1(InstanceCacheManager.java:166) at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:572) at java.base/java.util.concurrent.FutureTask.runAndReset$$$capture(FutureTask.java:358) at java.base/java.util.concurrent.FutureTask.runAndReset(FutureTask.java) at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:305) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1144) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:642) at java.base/java.lang.Thread.run(Thread.java:1583) All startup components are ready to accept request! java.lang.IllegalArgumentException: The connection string is invalid. Connection strings must start with either 'mongodb://' or 'mongodb+srv:// at com.mongodb.ConnectionString.<init>(ConnectionString.java:362) at com.mongodb.ConnectionString.<init>(ConnectionString.java:343) at com.mongodb.client.MongoClients.create(MongoClients.java:61) at com.huawei.cbgit.onlinedocsmgmt.MainApplicationTest.test(MainApplicationTest.java:55) at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:103) at java.base/java.lang.reflect.Method.invoke(Method.java:580) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:76) at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84) at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75) at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86) at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97) at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329) at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306) at org.junit.runners.ParentRunner.run(ParentRunner.java:413) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191) at org.junit.runner.JUnitCore.run(JUnitCore.java:137) at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69) at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38) at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11) at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35) at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:231) at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:55)
09-25
// // Source code recreated from a .class file by IntelliJ IDEA // (powered by FernFlower decompiler) // package org.springframework.boot; import java.lang.reflect.Constructor; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.stream.Collectors; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.BeanUtils; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.BeanNameGenerator; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.boot.Banner.Mode; import org.springframework.boot.context.properties.bind.Bindable; import org.springframework.boot.context.properties.bind.Binder; import org.springframework.boot.context.properties.source.ConfigurationPropertySources; import org.springframework.boot.convert.ApplicationConversionService; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextInitializer; import org.springframework.context.ApplicationListener; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.GenericApplicationContext; import org.springframework.core.GenericTypeResolver; import org.springframework.core.Ordered; import org.springframework.core.annotation.AnnotationAwareOrderComparator; import org.springframework.core.env.CompositePropertySource; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.Environment; import org.springframework.core.env.MutablePropertySources; import org.springframework.core.env.PropertySource; import org.springframework.core.env.SimpleCommandLinePropertySource; import org.springframework.core.env.StandardEnvironment; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.support.SpringFactoriesLoader; import org.springframework.core.metrics.ApplicationStartup; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.CollectionUtils; import org.springframework.util.ObjectUtils; import org.springframework.util.ReflectionUtils; import org.springframework.util.StringUtils; public class SpringApplication { public static final String BANNER_LOCATION_PROPERTY_VALUE = "banner.txt"; public static final String BANNER_LOCATION_PROPERTY = "spring.banner.location"; private static final String SYSTEM_PROPERTY_JAVA_AWT_HEADLESS = "java.awt.headless"; private static final Log logger = LogFactory.getLog(SpringApplication.class); static final SpringApplicationShutdownHook shutdownHook = new SpringApplicationShutdownHook(); private Set<Class<?>> primarySources; private Set<String> sources; private Class<?> mainApplicationClass; private Banner.Mode bannerMode; private boolean logStartupInfo; private boolean addCommandLineProperties; private boolean addConversionService; private Banner banner; private ResourceLoader resourceLoader; private BeanNameGenerator beanNameGenerator; private ConfigurableEnvironment environment; private WebApplicationType webApplicationType; private boolean headless; private boolean registerShutdownHook; private List<ApplicationContextInitializer<?>> initializers; private List<ApplicationListener<?>> listeners; private Map<String, Object> defaultProperties; private List<BootstrapRegistryInitializer> bootstrapRegistryInitializers; private Set<String> additionalProfiles; private boolean allowBeanDefinitionOverriding; private boolean allowCircularReferences; private boolean isCustomEnvironment; private boolean lazyInitialization; private String environmentPrefix; private ApplicationContextFactory applicationContextFactory; private ApplicationStartup applicationStartup; public SpringApplication(Class<?>... primarySources) { this((ResourceLoader)null, primarySources); } public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) { this.sources = new LinkedHashSet(); this.bannerMode = Mode.CONSOLE; this.logStartupInfo = true; this.addCommandLineProperties = true; this.addConversionService = true; this.headless = true; this.registerShutdownHook = true; this.additionalProfiles = Collections.emptySet(); this.isCustomEnvironment = false; this.lazyInitialization = false; this.applicationContextFactory = ApplicationContextFactory.DEFAULT; this.applicationStartup = ApplicationStartup.DEFAULT; this.resourceLoader = resourceLoader; Assert.notNull(primarySources, "PrimarySources must not be null"); this.primarySources = new LinkedHashSet(Arrays.asList(primarySources)); this.webApplicationType = WebApplicationType.deduceFromClasspath(); this.bootstrapRegistryInitializers = new ArrayList(this.getSpringFactoriesInstances(BootstrapRegistryInitializer.class)); this.setInitializers(this.getSpringFactoriesInstances(ApplicationContextInitializer.class)); this.setListeners(this.getSpringFactoriesInstances(ApplicationListener.class)); this.mainApplicationClass = this.deduceMainApplicationClass(); } private Class<?> deduceMainApplicationClass() { try { StackTraceElement[] stackTrace = (new RuntimeException()).getStackTrace(); StackTraceElement[] var2 = stackTrace; int var3 = stackTrace.length; for(int var4 = 0; var4 < var3; ++var4) { StackTraceElement stackTraceElement = var2[var4]; if ("main".equals(stackTraceElement.getMethodName())) { return Class.forName(stackTraceElement.getClassName()); } } } catch (ClassNotFoundException var6) { } return null; } public ConfigurableApplicationContext run(String... args) { long startTime = System.nanoTime(); DefaultBootstrapContext bootstrapContext = this.createBootstrapContext(); ConfigurableApplicationContext context = null; this.configureHeadlessProperty(); SpringApplicationRunListeners listeners = this.getRunListeners(args); listeners.starting(bootstrapContext, this.mainApplicationClass); try { ApplicationArguments applicationArguments = new DefaultApplicationArguments(args); ConfigurableEnvironment environment = this.prepareEnvironment(listeners, bootstrapContext, applicationArguments); this.configureIgnoreBeanInfo(environment); Banner printedBanner = this.printBanner(environment); context = this.createApplicationContext(); context.setApplicationStartup(this.applicationStartup); this.prepareContext(bootstrapContext, context, environment, listeners, applicationArguments, printedBanner); this.refreshContext(context); this.afterRefresh(context, applicationArguments); Duration timeTakenToStartup = Duration.ofNanos(System.nanoTime() - startTime); if (this.logStartupInfo) { (new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), timeTakenToStartup); } listeners.started(context, timeTakenToStartup); this.callRunners(context, applicationArguments); } catch (Throwable var12) { this.handleRunFailure(context, var12, listeners); throw new IllegalStateException(var12); } try { Duration timeTakenToReady = Duration.ofNanos(System.nanoTime() - startTime); listeners.ready(context, timeTakenToReady); return context; } catch (Throwable var11) { this.handleRunFailure(context, var11, (SpringApplicationRunListeners)null); throw new IllegalStateException(var11); } } private DefaultBootstrapContext createBootstrapContext() { DefaultBootstrapContext bootstrapContext = new DefaultBootstrapContext(); this.bootstrapRegistryInitializers.forEach((initializer) -> { initializer.initialize(bootstrapContext); }); return bootstrapContext; } private ConfigurableEnvironment prepareEnvironment(SpringApplicationRunListeners listeners, DefaultBootstrapContext bootstrapContext, ApplicationArguments applicationArguments) { ConfigurableEnvironment environment = this.getOrCreateEnvironment(); this.configureEnvironment((ConfigurableEnvironment)environment, applicationArguments.getSourceArgs()); ConfigurationPropertySources.attach((Environment)environment); listeners.environmentPrepared(bootstrapContext, (ConfigurableEnvironment)environment); DefaultPropertiesPropertySource.moveToEnd((ConfigurableEnvironment)environment); Assert.state(!((ConfigurableEnvironment)environment).containsProperty("spring.main.environment-prefix"), "Environment prefix cannot be set via properties."); this.bindToSpringApplication((ConfigurableEnvironment)environment); if (!this.isCustomEnvironment) { environment = this.convertEnvironment((ConfigurableEnvironment)environment); } ConfigurationPropertySources.attach((Environment)environment); return (ConfigurableEnvironment)environment; } /** @deprecated */ @Deprecated public StandardEnvironment convertEnvironment(ConfigurableEnvironment environment) { return (new EnvironmentConverter(this.getClassLoader())).convertEnvironmentIfNecessary(environment, this.deduceEnvironmentClass()); } private Class<? extends StandardEnvironment> deduceEnvironmentClass() { switch (this.webApplicationType) { case SERVLET: return ApplicationServletEnvironment.class; case REACTIVE: return ApplicationReactiveWebEnvironment.class; default: return ApplicationEnvironment.class; } } private void prepareContext(DefaultBootstrapContext bootstrapContext, ConfigurableApplicationContext context, ConfigurableEnvironment environment, SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments, Banner printedBanner) { context.setEnvironment(environment); this.postProcessApplicationContext(context); this.applyInitializers(context); listeners.contextPrepared(context); bootstrapContext.close(context); if (this.logStartupInfo) { this.logStartupInfo(context.getParent() == null); this.logStartupProfileInfo(context); } ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); beanFactory.registerSingleton("springApplicationArguments", applicationArguments); if (printedBanner != null) { beanFactory.registerSingleton("springBootBanner", printedBanner); } if (beanFactory instanceof AbstractAutowireCapableBeanFactory) { ((AbstractAutowireCapableBeanFactory)beanFactory).setAllowCircularReferences(this.allowCircularReferences); if (beanFactory instanceof DefaultListableBeanFactory) { ((DefaultListableBeanFactory)beanFactory).setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding); } } if (this.lazyInitialization) { context.addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor()); } context.addBeanFactoryPostProcessor(new PropertySourceOrderingBeanFactoryPostProcessor(context)); Set<Object> sources = this.getAllSources(); Assert.notEmpty(sources, "Sources must not be empty"); this.load(context, sources.toArray(new Object[0])); listeners.contextLoaded(context); } private void refreshContext(ConfigurableApplicationContext context) { if (this.registerShutdownHook) { shutdownHook.registerApplicationContext(context); } this.refresh(context); } private void configureHeadlessProperty() { System.setProperty("java.awt.headless", System.getProperty("java.awt.headless", Boolean.toString(this.headless))); } private SpringApplicationRunListeners getRunListeners(String[] args) { Class<?>[] types = new Class[]{SpringApplication.class, String[].class}; return new SpringApplicationRunListeners(logger, this.getSpringFactoriesInstances(SpringApplicationRunListener.class, types, this, args), this.applicationStartup); } private <T> Collection<T> getSpringFactoriesInstances(Class<T> type) { return this.getSpringFactoriesInstances(type, new Class[0]); } private <T> Collection<T> getSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, Object... args) { ClassLoader classLoader = this.getClassLoader(); Set<String> names = new LinkedHashSet(SpringFactoriesLoader.loadFactoryNames(type, classLoader)); List<T> instances = this.createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names); AnnotationAwareOrderComparator.sort(instances); return instances; } private <T> List<T> createSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, ClassLoader classLoader, Object[] args, Set<String> names) { List<T> instances = new ArrayList(names.size()); Iterator var7 = names.iterator(); while(var7.hasNext()) { String name = (String)var7.next(); try { Class<?> instanceClass = ClassUtils.forName(name, classLoader); Assert.isAssignable(type, instanceClass); Constructor<?> constructor = instanceClass.getDeclaredConstructor(parameterTypes); T instance = BeanUtils.instantiateClass(constructor, args); instances.add(instance); } catch (Throwable var12) { throw new IllegalArgumentException("Cannot instantiate " + type + " : " + name, var12); } } return instances; } private ConfigurableEnvironment getOrCreateEnvironment() { if (this.environment != null) { return this.environment; } else { switch (this.webApplicationType) { case SERVLET: return new ApplicationServletEnvironment(); case REACTIVE: return new ApplicationReactiveWebEnvironment(); default: return new ApplicationEnvironment(); } } } protected void configureEnvironment(ConfigurableEnvironment environment, String[] args) { if (this.addConversionService) { environment.setConversionService(new ApplicationConversionService()); } this.configurePropertySources(environment, args); this.configureProfiles(environment, args); } protected void configurePropertySources(ConfigurableEnvironment environment, String[] args) { MutablePropertySources sources = environment.getPropertySources(); if (!CollectionUtils.isEmpty(this.defaultProperties)) { DefaultPropertiesPropertySource.addOrMerge(this.defaultProperties, sources); } if (this.addCommandLineProperties && args.length > 0) { String name = "commandLineArgs"; if (sources.contains(name)) { PropertySource<?> source = sources.get(name); CompositePropertySource composite = new CompositePropertySource(name); composite.addPropertySource(new SimpleCommandLinePropertySource("springApplicationCommandLineArgs", args)); composite.addPropertySource(source); sources.replace(name, composite); } else { sources.addFirst(new SimpleCommandLinePropertySource(args)); } } } protected void configureProfiles(ConfigurableEnvironment environment, String[] args) { } private void configureIgnoreBeanInfo(ConfigurableEnvironment environment) { if (System.getProperty("spring.beaninfo.ignore") == null) { Boolean ignore = (Boolean)environment.getProperty("spring.beaninfo.ignore", Boolean.class, Boolean.TRUE); System.setProperty("spring.beaninfo.ignore", ignore.toString()); } } protected void bindToSpringApplication(ConfigurableEnvironment environment) { try { Binder.get(environment).bind("spring.main", Bindable.ofInstance(this)); } catch (Exception var3) { throw new IllegalStateException("Cannot bind to SpringApplication", var3); } } private Banner printBanner(ConfigurableEnvironment environment) { if (this.bannerMode == Mode.OFF) { return null; } else { ResourceLoader resourceLoader = this.resourceLoader != null ? this.resourceLoader : new DefaultResourceLoader((ClassLoader)null); SpringApplicationBannerPrinter bannerPrinter = new SpringApplicationBannerPrinter((ResourceLoader)resourceLoader, this.banner); return this.bannerMode == Mode.LOG ? bannerPrinter.print(environment, this.mainApplicationClass, logger) : bannerPrinter.print(environment, this.mainApplicationClass, System.out); } } protected ConfigurableApplicationContext createApplicationContext() { return this.applicationContextFactory.create(this.webApplicationType); } protected void postProcessApplicationContext(ConfigurableApplicationContext context) { if (this.beanNameGenerator != null) { context.getBeanFactory().registerSingleton("org.springframework.context.annotation.internalConfigurationBeanNameGenerator", this.beanNameGenerator); } if (this.resourceLoader != null) { if (context instanceof GenericApplicationContext) { ((GenericApplicationContext)context).setResourceLoader(this.resourceLoader); } if (context instanceof DefaultResourceLoader) { ((DefaultResourceLoader)context).setClassLoader(this.resourceLoader.getClassLoader()); } } if (this.addConversionService) { context.getBeanFactory().setConversionService(context.getEnvironment().getConversionService()); } } protected void applyInitializers(ConfigurableApplicationContext context) { Iterator var2 = this.getInitializers().iterator(); while(var2.hasNext()) { ApplicationContextInitializer initializer = (ApplicationContextInitializer)var2.next(); Class<?> requiredType = GenericTypeResolver.resolveTypeArgument(initializer.getClass(), ApplicationContextInitializer.class); Assert.isInstanceOf(requiredType, context, "Unable to call initializer."); initializer.initialize(context); } } protected void logStartupInfo(boolean isRoot) { if (isRoot) { (new StartupInfoLogger(this.mainApplicationClass)).logStarting(this.getApplicationLog()); } } protected void logStartupProfileInfo(ConfigurableApplicationContext context) { Log log = this.getApplicationLog(); if (log.isInfoEnabled()) { List<String> activeProfiles = this.quoteProfiles(context.getEnvironment().getActiveProfiles()); if (ObjectUtils.isEmpty(activeProfiles)) { List<String> defaultProfiles = this.quoteProfiles(context.getEnvironment().getDefaultProfiles()); String message = String.format("%s default %s: ", defaultProfiles.size(), defaultProfiles.size() <= 1 ? "profile" : "profiles"); log.info("No active profile set, falling back to " + message + StringUtils.collectionToDelimitedString(defaultProfiles, ", ")); } else { String message = activeProfiles.size() == 1 ? "1 profile is active: " : activeProfiles.size() + " profiles are active: "; log.info("The following " + message + StringUtils.collectionToDelimitedString(activeProfiles, ", ")); } } } private List<String> quoteProfiles(String[] profiles) { return (List)Arrays.stream(profiles).map((profile) -> { return "\"" + profile + "\""; }).collect(Collectors.toList()); } protected Log getApplicationLog() { return this.mainApplicationClass == null ? logger : LogFactory.getLog(this.mainApplicationClass); } protected void load(ApplicationContext context, Object[] sources) { if (logger.isDebugEnabled()) { logger.debug("Loading source " + StringUtils.arrayToCommaDelimitedString(sources)); } BeanDefinitionLoader loader = this.createBeanDefinitionLoader(this.getBeanDefinitionRegistry(context), sources); if (this.beanNameGenerator != null) { loader.setBeanNameGenerator(this.beanNameGenerator); } if (this.resourceLoader != null) { loader.setResourceLoader(this.resourceLoader); } if (this.environment != null) { loader.setEnvironment(this.environment); } loader.load(); } public ResourceLoader getResourceLoader() { return this.resourceLoader; } public ClassLoader getClassLoader() { return this.resourceLoader != null ? this.resourceLoader.getClassLoader() : ClassUtils.getDefaultClassLoader(); } private BeanDefinitionRegistry getBeanDefinitionRegistry(ApplicationContext context) { if (context instanceof BeanDefinitionRegistry) { return (BeanDefinitionRegistry)context; } else if (context instanceof AbstractApplicationContext) { return (BeanDefinitionRegistry)((AbstractApplicationContext)context).getBeanFactory(); } else { throw new IllegalStateException("Could not locate BeanDefinitionRegistry"); } } protected BeanDefinitionLoader createBeanDefinitionLoader(BeanDefinitionRegistry registry, Object[] sources) { return new BeanDefinitionLoader(registry, sources); } protected void refresh(ConfigurableApplicationContext applicationContext) { applicationContext.refresh(); } protected void afterRefresh(ConfigurableApplicationContext context, ApplicationArguments args) { } private void callRunners(ApplicationContext context, ApplicationArguments args) { List<Object> runners = new ArrayList(); runners.addAll(context.getBeansOfType(ApplicationRunner.class).values()); runners.addAll(context.getBeansOfType(CommandLineRunner.class).values()); AnnotationAwareOrderComparator.sort(runners); Iterator var4 = (new LinkedHashSet(runners)).iterator(); while(var4.hasNext()) { Object runner = var4.next(); if (runner instanceof ApplicationRunner) { this.callRunner((ApplicationRunner)runner, args); } if (runner instanceof CommandLineRunner) { this.callRunner((CommandLineRunner)runner, args); } } } private void callRunner(ApplicationRunner runner, ApplicationArguments args) { try { runner.run(args); } catch (Exception var4) { throw new IllegalStateException("Failed to execute ApplicationRunner", var4); } } private void callRunner(CommandLineRunner runner, ApplicationArguments args) { try { runner.run(args.getSourceArgs()); } catch (Exception var4) { throw new IllegalStateException("Failed to execute CommandLineRunner", var4); } } private void handleRunFailure(ConfigurableApplicationContext context, Throwable exception, SpringApplicationRunListeners listeners) { try { try { this.handleExitCode(context, exception); if (listeners != null) { listeners.failed(context, exception); } } finally { this.reportFailure(this.getExceptionReporters(context), exception); if (context != null) { context.close(); shutdownHook.deregisterFailedApplicationContext(context); } } } catch (Exception var8) { logger.warn("Unable to close ApplicationContext", var8); } ReflectionUtils.rethrowRuntimeException(exception); } private Collection<SpringBootExceptionReporter> getExceptionReporters(ConfigurableApplicationContext context) { try { return this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[]{ConfigurableApplicationContext.class}, context); } catch (Throwable var3) { return Collections.emptyList(); } } private void reportFailure(Collection<SpringBootExceptionReporter> exceptionReporters, Throwable failure) { try { Iterator var3 = exceptionReporters.iterator(); while(var3.hasNext()) { SpringBootExceptionReporter reporter = (SpringBootExceptionReporter)var3.next(); if (reporter.reportException(failure)) { this.registerLoggedException(failure); return; } } } catch (Throwable var5) { } if (logger.isErrorEnabled()) { logger.error("Application run failed", failure); this.registerLoggedException(failure); } } protected void registerLoggedException(Throwable exception) { SpringBootExceptionHandler handler = this.getSpringBootExceptionHandler(); if (handler != null) { handler.registerLoggedException(exception); } } private void handleExitCode(ConfigurableApplicationContext context, Throwable exception) { int exitCode = this.getExitCodeFromException(context, exception); if (exitCode != 0) { if (context != null) { context.publishEvent(new ExitCodeEvent(context, exitCode)); } SpringBootExceptionHandler handler = this.getSpringBootExceptionHandler(); if (handler != null) { handler.registerExitCode(exitCode); } } } private int getExitCodeFromException(ConfigurableApplicationContext context, Throwable exception) { int exitCode = this.getExitCodeFromMappedException(context, exception); if (exitCode == 0) { exitCode = this.getExitCodeFromExitCodeGeneratorException(exception); } return exitCode; } private int getExitCodeFromMappedException(ConfigurableApplicationContext context, Throwable exception) { if (context != null && context.isActive()) { ExitCodeGenerators generators = new ExitCodeGenerators(); Collection<ExitCodeExceptionMapper> beans = context.getBeansOfType(ExitCodeExceptionMapper.class).values(); generators.addAll(exception, beans); return generators.getExitCode(); } else { return 0; } } private int getExitCodeFromExitCodeGeneratorException(Throwable exception) { if (exception == null) { return 0; } else { return exception instanceof ExitCodeGenerator ? ((ExitCodeGenerator)exception).getExitCode() : this.getExitCodeFromExitCodeGeneratorException(exception.getCause()); } } SpringBootExceptionHandler getSpringBootExceptionHandler() { return this.isMainThread(Thread.currentThread()) ? SpringBootExceptionHandler.forCurrentThread() : null; } private boolean isMainThread(Thread currentThread) { return ("main".equals(currentThread.getName()) || "restartedMain".equals(currentThread.getName())) && "main".equals(currentThread.getThreadGroup().getName()); } public Class<?> getMainApplicationClass() { return this.mainApplicationClass; } public void setMainApplicationClass(Class<?> mainApplicationClass) { this.mainApplicationClass = mainApplicationClass; } public WebApplicationType getWebApplicationType() { return this.webApplicationType; } public void setWebApplicationType(WebApplicationType webApplicationType) { Assert.notNull(webApplicationType, "WebApplicationType must not be null"); this.webApplicationType = webApplicationType; } public void setAllowBeanDefinitionOverriding(boolean allowBeanDefinitionOverriding) { this.allowBeanDefinitionOverriding = allowBeanDefinitionOverriding; } public void setAllowCircularReferences(boolean allowCircularReferences) { this.allowCircularReferences = allowCircularReferences; } public void setLazyInitialization(boolean lazyInitialization) { this.lazyInitialization = lazyInitialization; } public void setHeadless(boolean headless) { this.headless = headless; } public void setRegisterShutdownHook(boolean registerShutdownHook) { this.registerShutdownHook = registerShutdownHook; } public void setBanner(Banner banner) { this.banner = banner; } public void setBannerMode(Banner.Mode bannerMode) { this.bannerMode = bannerMode; } public void setLogStartupInfo(boolean logStartupInfo) { this.logStartupInfo = logStartupInfo; } public void setAddCommandLineProperties(boolean addCommandLineProperties) { this.addCommandLineProperties = addCommandLineProperties; } public void setAddConversionService(boolean addConversionService) { this.addConversionService = addConversionService; } public void addBootstrapRegistryInitializer(BootstrapRegistryInitializer bootstrapRegistryInitializer) { Assert.notNull(bootstrapRegistryInitializer, "BootstrapRegistryInitializer must not be null"); this.bootstrapRegistryInitializers.addAll(Arrays.asList(bootstrapRegistryInitializer)); } public void setDefaultProperties(Map<String, Object> defaultProperties) { this.defaultProperties = defaultProperties; } public void setDefaultProperties(Properties defaultProperties) { this.defaultProperties = new HashMap(); Iterator var2 = Collections.list(defaultProperties.propertyNames()).iterator(); while(var2.hasNext()) { Object key = var2.next(); this.defaultProperties.put((String)key, defaultProperties.get(key)); } } public void setAdditionalProfiles(String... profiles) { this.additionalProfiles = Collections.unmodifiableSet(new LinkedHashSet(Arrays.asList(profiles))); } public Set<String> getAdditionalProfiles() { return this.additionalProfiles; } public void setBeanNameGenerator(BeanNameGenerator beanNameGenerator) { this.beanNameGenerator = beanNameGenerator; } public void setEnvironment(ConfigurableEnvironment environment) { this.isCustomEnvironment = true; this.environment = environment; } public void addPrimarySources(Collection<Class<?>> additionalPrimarySources) { this.primarySources.addAll(additionalPrimarySources); } public Set<String> getSources() { return this.sources; } public void setSources(Set<String> sources) { Assert.notNull(sources, "Sources must not be null"); this.sources = new LinkedHashSet(sources); } public Set<Object> getAllSources() { Set<Object> allSources = new LinkedHashSet(); if (!CollectionUtils.isEmpty(this.primarySources)) { allSources.addAll(this.primarySources); } if (!CollectionUtils.isEmpty(this.sources)) { allSources.addAll(this.sources); } return Collections.unmodifiableSet(allSources); } public void setResourceLoader(ResourceLoader resourceLoader) { Assert.notNull(resourceLoader, "ResourceLoader must not be null"); this.resourceLoader = resourceLoader; } public String getEnvironmentPrefix() { return this.environmentPrefix; } public void setEnvironmentPrefix(String environmentPrefix) { this.environmentPrefix = environmentPrefix; } public void setApplicationContextFactory(ApplicationContextFactory applicationContextFactory) { this.applicationContextFactory = applicationContextFactory != null ? applicationContextFactory : ApplicationContextFactory.DEFAULT; } public void setInitializers(Collection<? extends ApplicationContextInitializer<?>> initializers) { this.initializers = new ArrayList(initializers); } public void addInitializers(ApplicationContextInitializer<?>... initializers) { this.initializers.addAll(Arrays.asList(initializers)); } public Set<ApplicationContextInitializer<?>> getInitializers() { return asUnmodifiableOrderedSet(this.initializers); } public void setListeners(Collection<? extends ApplicationListener<?>> listeners) { this.listeners = new ArrayList(listeners); } public void addListeners(ApplicationListener<?>... listeners) { this.listeners.addAll(Arrays.asList(listeners)); } public Set<ApplicationListener<?>> getListeners() { return asUnmodifiableOrderedSet(this.listeners); } public void setApplicationStartup(ApplicationStartup applicationStartup) { this.applicationStartup = applicationStartup != null ? applicationStartup : ApplicationStartup.DEFAULT; } public ApplicationStartup getApplicationStartup() { return this.applicationStartup; } public static SpringApplicationShutdownHandlers getShutdownHandlers() { return shutdownHook.getHandlers(); } public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) { return run(new Class[]{primarySource}, args); } public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) { return (new SpringApplication(primarySources)).run(args); } public static void main(String[] args) throws Exception { run(new Class[0], args); } public static int exit(ApplicationContext context, ExitCodeGenerator... exitCodeGenerators) { Assert.notNull(context, "Context must not be null"); int exitCode = 0; try { try { ExitCodeGenerators generators = new ExitCodeGenerators(); Collection<ExitCodeGenerator> beans = context.getBeansOfType(ExitCodeGenerator.class).values(); generators.addAll(exitCodeGenerators); generators.addAll(beans); exitCode = generators.getExitCode(); if (exitCode != 0) { context.publishEvent(new ExitCodeEvent(context, exitCode)); } } finally { close(context); } } catch (Exception var9) { var9.printStackTrace(); exitCode = exitCode != 0 ? exitCode : 1; } return exitCode; } private static void close(ApplicationContext context) { if (context instanceof ConfigurableApplicationContext) { ConfigurableApplicationContext closable = (ConfigurableApplicationContext)context; closable.close(); } } private static <E> Set<E> asUnmodifiableOrderedSet(Collection<E> elements) { List<E> list = new ArrayList(elements); list.sort(AnnotationAwareOrderComparator.INSTANCE); return new LinkedHashSet(list); } private static class PropertySourceOrderingBeanFactoryPostProcessor implements BeanFactoryPostProcessor, Ordered { private final ConfigurableApplicationContext context; PropertySourceOrderingBeanFactoryPostProcessor(ConfigurableApplicationContext context) { this.context = context; } public int getOrder() { return Integer.MIN_VALUE; } public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { DefaultPropertiesPropertySource.moveToEnd(this.context.getEnvironment()); } } } 这里面哪一段代码是加载application.yml中的参数的
09-09
<think>首先,用户的问题是关于Java中使用iterator.remove方法时遇到java.lang.IllegalStateException: null的解决方案。用户提供了几个引用,我需要基于这些引用来回答。 回顾引用内容: - 引用[1]:指出在使用Iterator.remove()时,必须先调用next()方法迭代出元素,然后才能调用remove()方法。否则,可能会抛出IllegalStateException异常。 - 引用[2]:解释了Iterator.remove()方法的源码,说明如果lastRet < 0,就会抛出IllegalStateException。lastRet是通过next()方法设置的。 - 引用[3]:确认了直接调用iterator.remove()会导致异常,需要先调用next()。 - 引用[4]:提供了一个具体例子,展示了如何在循环中正确使用iterator.remove(),避免多次调用remove()而没有对应的next()。 - 引用[5]:展示了一个错误代码示例,其中直接调用it.remove()而没有先调用it.next()。 关键点: - IllegalStateException发生在调用Iterator.remove()时,如果没有先调用next()方法,或者在调用next()之后已经调用了remove()一次以上。 - 解决方案:每次调用remove()之前,必须调用一次next()来定位到元素。 我的回答需要: - 使用中文。 - 结构清晰,逐步解决问题。 - 引用相关段落。 - 确保回答真实可靠。 - 遵循系统级指令:使用$...$和$$...$$格式公式(但这里是Java问题,可能不需要数学公式,除非涉及算法)。 - 最后生成相关问题。 回答结构: 1. **介绍问题**:简要解释IllegalStateException的原因。 2. **原因分析**:基于引用,阐述为什么会出现这个异常。 3. **解决方案**:提供正确的使用Iterator.remove()的方法。 4. **示例代码**:展示正确和错误的代码对比。 5. **注意事项**:提醒其他可能的问题。 6. **生成相关问题**:在末尾列出相关问题。 确保引用: - 在回答中,自然地添加引用标识,如[^1]。 现在,构建回答: - 开头:复述用户问题。 - 主体:展开原因和解决方案。 - 结尾:生成相关问题。 相关问题示例: 1. 如何避免在Java迭代器中使用remove()方法时的并发修改异常? 2. Java中Iterator和ListIterator的区别是什么? 3. 在并发环境中如何安全地使用迭代器? 最终回答: </think>### Java中使用Iterator.remove()方法报错`java.lang.IllegalStateException: null`的解决方案 在使用Java的`Iterator.remove()`方法时,如果直接调用`remove()`而未遵循特定规则,会导致`java.lang.IllegalStateException: null`异常。这个异常的根本原因是迭代器在执行`remove()`方法前没有正确调用`next()`方法,或者重复调用`remove()`而不重新定位元素。下面我将基于提供的引用内容,逐步解释原因并提供解决办法。 #### 1. **问题原因分析** - **缺少`next()`调用**:迭代器要求每次调用`remove()`之前必须先调用`next()`方法,该方法会将光标移动到下一个元素并设置`lastRet`字段(用于标记最近访问的元素位置)。如果直接调用`remove()`而没有先调用`next()`,迭代器无法确定要删除的元素,从而抛出`IllegalStateException`[^1][^2]。 - **重复调用`remove()`**:在一次`next()`调用后,只能调用一次`remove()`。如果多次调用`remove()`而不重新调用`next()`,迭代器会检测到无效状态(`lastRet < 0`),导致异常[^2][^4]。 - **源码机制**:在`Iterator.remove()`的源码中,会检查`lastRet`的值。如果`lastRet < 0`(表示没有通过`next()`定位元素),就直接抛出`IllegalStateException`。同时,`remove()`操作会重置`lastRet`为-1,防止连续删除[^2][^5]。 #### 2. **正确解决方案** 要避免`IllegalStateException`,需严格遵守迭代器的使用规范: - **调用`remove()`前必须先调用`next()`**:每次删除元素前,必须使用`next()`迭代到目标元素。 - **每次`next()`仅调用一次`remove()`**:确保在每次`next()`调用后,最多只调用一次`remove()`。 - **在循环中正确处理**:遍历集合时,使用`while(it.hasNext())`循环,确保每个删除操作都与`next()`配对。 ##### 正确代码示例 以下是一个安全的`Iterator.remove()`使用示例,演示了如何在循环中删除元素: ```java List<String> list = new ArrayList<>(); list.add("A"); list.add("B"); list.add("C"); Iterator<String> it = list.iterator(); while (it.hasNext()) { String element = it.next(); // 必须调用next()定位元素 if (element.equals("B")) { // 条件判断 it.remove(); // 安全删除元素 } } System.out.println(list); // 输出: [A, C] ``` - **关键点**:在`it.remove()`之前,必须调用`it.next()`。每次循环仅调用一次`remove()`,避免重复删除[^1][^4]。 ##### 常见错误代码及修复 - **错误示例**:直接调用`remove()`而不调用`next()`,如图引用[^5]: ```java List<String> list = new ArrayList<>(); list.add("111"); Iterator<String> it = list.iterator(); it.remove(); // 抛出IllegalStateException: 缺少next()调用 ``` - **修复**:在`remove()`前添加`it.next()`: ```java it.next(); // 定位到元素 it.remove(); // 安全删除 ``` - **错误示例**:在循环中多次调用`remove()`: ```java while (it.hasNext()) { if (condition1) { it.remove(); // 第一次调用正确 } if (condition2) { it.remove(); // 第二次调用抛出异常:lastRet已重置 } } ``` - **修复**:确保每个循环只调用一次`remove()`,或合并条件: ```java while (it.hasNext()) { String element = it.next(); if (condition1 || condition2) { // 合并条件 it.remove(); // 只调用一次 } } ``` #### 3. **额外注意事项** - **并发修改问题**:迭代器在遍历时,如果底层集合被其他线程修改(如直接调用`List.remove()`),可能引发`ConcurrentModificationException`。请始终使用`Iterator.remove()`进行删除,而非集合自身的`remove()`方法[^2][^4]。 - **性能优化**:对于大数据集,`Iterator.remove()`的时间复杂度为$O(n)$(线性时间)。如果需要高效删除,考虑使用`ListIterator`(支持双向遍历)。 - **调试建议**:在开发中,使用IDE的调试器检查`lastRet`状态,确保其在调用`remove()`时不为负值。 #### 4. **总结** `java.lang.IllegalStateException: null`异常是由于迭代器`remove()`方法使用不规范导致的。核心解决方法是:**每次调用`remove()`前必须调用一次`next()`方法,并且每个`next()`后只能调用一次`remove()`**。遵循此规则,可以安全地在Java中使用迭代器删除元素[^1][^2][^4]。
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ZHOU_VIP

您的鼓励将是我创作最大的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值