分类 开发篇 下的文章

假如你要使用if语句判断Query类的成员变量in是否为null,你可能会这么写: <if test="null != query.in"></if>(错误)


正确的做法是把Query类的in变量名改成其它名字,比如改成contains <if test="null != query.contains"></if>(正确)

我打算把Spring Cloud Alibaba升级个版本,看看有什么新特性,结果升级后死活启动不了。

事情是这样的,跟往常一样,我先去Spring官网找到Spring Cloud Alibaba的最新的版本号,如下图所示:

可以看到最新的版本是2021.0.1.0

spring cloud alibaba.png

我默默记下这个版本号...
然后点了右上角的那只章鱼猫
Wiki里找到版本说明,如下图所示:
现在我知道了Spring Cloud Alibaba Version、Spring Cloud Version和Spring Boot Version三者版本对应关系了!

edition.png

我再次回到Spring官网,然后打开Spring Cloud Alibaba的Reference,根据文档,一顿操作。
其实大概就只有三步:

  1. 添加依赖
<!--在父工程添加以下依赖-->
<properties>
        <spring.cloud.version>2021.0.1</spring.cloud.version>
        <spring-boot-dependencies.version>2.6.3</spring-boot-dependencies.version>
        <com.alibaba.cloud.spring-cloud-alibaba-dependencies.version>2021.0.1.0
        </com.alibaba.cloud.spring-cloud-alibaba-dependencies.version>
</properties>
<dependencyManagement>
        <dependencies>
            <!--官网里使用spring-boot-starter-parent作为父工程而没有导入这条依赖,实际作用相同-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot-dependencies.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring.cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>${com.alibaba.cloud.spring-cloud-alibaba-dependencies.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
</dependencyManagement>
<!--在module中添加以下依赖-->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
  1. 配置yaml
spring:
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848
  1. 在主类上添加@EnableDiscoveryClient注解

激动的心,颤抖的手,点击运行!(提前启动好了Nacos

2022-09-05 00:04:32.047  INFO 37828 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2022-09-05 00:04:32.047  INFO 37828 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.56]
2022-09-05 00:04:32.109  INFO 37828 --- [  restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2022-09-05 00:04:32.109  INFO 37828 --- [  restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1320 ms
2022-09-05 00:04:32.504  WARN 37828 --- [  restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerAdapter' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter]: Factory method 'requestMappingHandlerAdapter' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'messageConverters' defined in class path resource [org/springframework/boot/autoconfigure/http/HttpMessageConvertersAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.autoconfigure.http.HttpMessageConverters]: Factory method 'messageConverters' threw exception; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'mappingJackson2HttpMessageConverter' defined in class path resource [org/springframework/boot/autoconfigure/http/JacksonHttpMessageConvertersConfiguration$MappingJackson2HttpMessageConverterConfiguration.class]: Unsatisfied dependency expressed through method 'mappingJackson2HttpMessageConverter' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jacksonObjectMapper' defined in class path resource [org/springframework/boot/autoconfigure/jackson/JacksonAutoConfiguration$JacksonObjectMapperConfiguration.class]: Post-processing of merged bean definition failed; nested exception is java.lang.IllegalStateException: Failed to introspect Class [com.fasterxml.jackson.databind.ObjectMapper] from ClassLoader [jdk.internal.loader.ClassLoaders$AppClassLoader@2437c6dc]
2022-09-05 00:04:32.507  INFO 37828 --- [  restartedMain] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2022-09-05 00:04:32.523  INFO 37828 --- [  restartedMain] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2022-09-05 00:04:32.551 ERROR 37828 --- [  restartedMain] o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerAdapter' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter]: Factory method 'requestMappingHandlerAdapter' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'messageConverters' defined in class path resource [org/springframework/boot/autoconfigure/http/HttpMessageConvertersAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.autoconfigure.http.HttpMessageConverters]: Factory method 'messageConverters' threw exception; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'mappingJackson2HttpMessageConverter' defined in class path resource [org/springframework/boot/autoconfigure/http/JacksonHttpMessageConvertersConfiguration$MappingJackson2HttpMessageConverterConfiguration.class]: Unsatisfied dependency expressed through method 'mappingJackson2HttpMessageConverter' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jacksonObjectMapper' defined in class path resource [org/springframework/boot/autoconfigure/jackson/JacksonAutoConfiguration$JacksonObjectMapperConfiguration.class]: Post-processing of merged bean definition failed; nested exception is java.lang.IllegalStateException: Failed to introspect Class [com.fasterxml.jackson.databind.ObjectMapper] from ClassLoader [jdk.internal.loader.ClassLoaders$AppClassLoader@2437c6dc]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:658) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:638) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1352) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1195) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:953) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918) ~[spring-context-5.3.15.jar:5.3.15]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.15.jar:5.3.15]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145) ~[spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:732) ~[spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:414) ~[spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:302) ~[spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1303) ~[spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1292) ~[spring-boot-2.6.3.jar:2.6.3]
    at cn.imcaoxuan.FileManagerApplication.main(FileManagerApplication.java:11) ~[classes/:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) ~[spring-boot-devtools-2.6.3.jar:2.6.3]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter]: Factory method 'requestMappingHandlerAdapter' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'messageConverters' defined in class path resource [org/springframework/boot/autoconfigure/http/HttpMessageConvertersAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.autoconfigure.http.HttpMessageConverters]: Factory method 'messageConverters' threw exception; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'mappingJackson2HttpMessageConverter' defined in class path resource [org/springframework/boot/autoconfigure/http/JacksonHttpMessageConvertersConfiguration$MappingJackson2HttpMessageConverterConfiguration.class]: Unsatisfied dependency expressed through method 'mappingJackson2HttpMessageConverter' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jacksonObjectMapper' defined in class path resource [org/springframework/boot/autoconfigure/jackson/JacksonAutoConfiguration$JacksonObjectMapperConfiguration.class]: Post-processing of merged bean definition failed; nested exception is java.lang.IllegalStateException: Failed to introspect Class [com.fasterxml.jackson.databind.ObjectMapper] from ClassLoader [jdk.internal.loader.ClassLoaders$AppClassLoader@2437c6dc]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:653) ~[spring-beans-5.3.15.jar:5.3.15]
    ... 24 common frames omitted
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'messageConverters' defined in class path resource [org/springframework/boot/autoconfigure/http/HttpMessageConvertersAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.autoconfigure.http.HttpMessageConverters]: Factory method 'messageConverters' threw exception; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'mappingJackson2HttpMessageConverter' defined in class path resource [org/springframework/boot/autoconfigure/http/JacksonHttpMessageConvertersConfiguration$MappingJackson2HttpMessageConverterConfiguration.class]: Unsatisfied dependency expressed through method 'mappingJackson2HttpMessageConverter' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jacksonObjectMapper' defined in class path resource [org/springframework/boot/autoconfigure/jackson/JacksonAutoConfiguration$JacksonObjectMapperConfiguration.class]: Post-processing of merged bean definition failed; nested exception is java.lang.IllegalStateException: Failed to introspect Class [com.fasterxml.jackson.databind.ObjectMapper] from ClassLoader [jdk.internal.loader.ClassLoaders$AppClassLoader@2437c6dc]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:658) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:638) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1352) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1195) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1389) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory$DependencyObjectProvider.getIfAvailable(DefaultListableBeanFactory.java:2030) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory$DependencyObjectProvider.ifAvailable(DefaultListableBeanFactory.java:2041) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter.configureMessageConverters(WebMvcAutoConfiguration.java:232) ~[spring-boot-autoconfigure-2.6.3.jar:2.6.3]
    at org.springframework.web.servlet.config.annotation.WebMvcConfigurerComposite.configureMessageConverters(WebMvcConfigurerComposite.java:137) ~[spring-webmvc-5.3.15.jar:5.3.15]
    at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration.configureMessageConverters(DelegatingWebMvcConfiguration.java:118) ~[spring-webmvc-5.3.15.jar:5.3.15]
    at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.getMessageConverters(WebMvcConfigurationSupport.java:865) ~[spring-webmvc-5.3.15.jar:5.3.15]
    at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.requestMappingHandlerAdapter(WebMvcConfigurationSupport.java:673) ~[spring-webmvc-5.3.15.jar:5.3.15]
    at org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$EnableWebMvcConfiguration.requestMappingHandlerAdapter(WebMvcAutoConfiguration.java:419) ~[spring-boot-autoconfigure-2.6.3.jar:2.6.3]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.3.15.jar:5.3.15]
    ... 25 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.autoconfigure.http.HttpMessageConverters]: Factory method 'messageConverters' threw exception; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'mappingJackson2HttpMessageConverter' defined in class path resource [org/springframework/boot/autoconfigure/http/JacksonHttpMessageConvertersConfiguration$MappingJackson2HttpMessageConverterConfiguration.class]: Unsatisfied dependency expressed through method 'mappingJackson2HttpMessageConverter' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jacksonObjectMapper' defined in class path resource [org/springframework/boot/autoconfigure/jackson/JacksonAutoConfiguration$JacksonObjectMapperConfiguration.class]: Post-processing of merged bean definition failed; nested exception is java.lang.IllegalStateException: Failed to introspect Class [com.fasterxml.jackson.databind.ObjectMapper] from ClassLoader [jdk.internal.loader.ClassLoaders$AppClassLoader@2437c6dc]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:653) ~[spring-beans-5.3.15.jar:5.3.15]
    ... 49 common frames omitted
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'mappingJackson2HttpMessageConverter' defined in class path resource [org/springframework/boot/autoconfigure/http/JacksonHttpMessageConvertersConfiguration$MappingJackson2HttpMessageConverterConfiguration.class]: Unsatisfied dependency expressed through method 'mappingJackson2HttpMessageConverter' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jacksonObjectMapper' defined in class path resource [org/springframework/boot/autoconfigure/jackson/JacksonAutoConfiguration$JacksonObjectMapperConfiguration.class]: Post-processing of merged bean definition failed; nested exception is java.lang.IllegalStateException: Failed to introspect Class [com.fasterxml.jackson.databind.ObjectMapper] from ClassLoader [jdk.internal.loader.ClassLoaders$AppClassLoader@2437c6dc]
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:800) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:541) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1352) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1195) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.addCandidateEntry(DefaultListableBeanFactory.java:1614) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1571) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveMultipleBeans(DefaultListableBeanFactory.java:1415) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1347) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory$DependencyObjectProvider.resolveStream(DefaultListableBeanFactory.java:2117) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory$DependencyObjectProvider.orderedStream(DefaultListableBeanFactory.java:2111) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration.messageConverters(HttpMessageConvertersAutoConfiguration.java:70) ~[spring-boot-autoconfigure-2.6.3.jar:2.6.3]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.3.15.jar:5.3.15]
    ... 50 common frames omitted
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jacksonObjectMapper' defined in class path resource [org/springframework/boot/autoconfigure/jackson/JacksonAutoConfiguration$JacksonObjectMapperConfiguration.class]: Post-processing of merged bean definition failed; nested exception is java.lang.IllegalStateException: Failed to introspect Class [com.fasterxml.jackson.databind.ObjectMapper] from ClassLoader [jdk.internal.loader.ClassLoaders$AppClassLoader@2437c6dc]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:597) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1389) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1309) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:887) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:791) ~[spring-beans-5.3.15.jar:5.3.15]
    ... 72 common frames omitted
Caused by: java.lang.IllegalStateException: Failed to introspect Class [com.fasterxml.jackson.databind.ObjectMapper] from ClassLoader [jdk.internal.loader.ClassLoaders$AppClassLoader@2437c6dc]
    at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:481) ~[spring-core-5.3.15.jar:5.3.15]
    at org.springframework.util.ReflectionUtils.doWithLocalMethods(ReflectionUtils.java:321) ~[spring-core-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.buildLifecycleMetadata(InitDestroyAnnotationBeanPostProcessor.java:232) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.findLifecycleMetadata(InitDestroyAnnotationBeanPostProcessor.java:210) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessMergedBeanDefinition(InitDestroyAnnotationBeanPostProcessor.java:149) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessMergedBeanDefinition(CommonAnnotationBeanPostProcessor.java:305) ~[spring-context-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyMergedBeanDefinitionPostProcessors(AbstractAutowireCapableBeanFactory.java:1116) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:594) ~[spring-beans-5.3.15.jar:5.3.15]
    ... 82 common frames omitted
Caused by: java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/exc/StreamWriteException
    at java.base/java.lang.Class.getDeclaredMethods0(Native Method) ~[na:na]
    at java.base/java.lang.Class.privateGetDeclaredMethods(Class.java:3167) ~[na:na]
    at java.base/java.lang.Class.getDeclaredMethods(Class.java:2310) ~[na:na]
    at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:463) ~[spring-core-5.3.15.jar:5.3.15]
    ... 89 common frames omitted
Caused by: java.lang.ClassNotFoundException: com.fasterxml.jackson.core.exc.StreamWriteException
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582) ~[na:na]
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178) ~[na:na]
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521) ~[na:na]
    ... 93 common frames omitted

Disconnected from the target VM, address: '127.0.0.1:59002', transport: 'socket'

Process finished with exit code 0

报错提示ClassNotFoundException,很明显,这种问题一般都是出现在缺少依赖的情况下的,但是jackson这个东西,我之前一直用的好好的啊!怎么突然就说找不到了呢?
我在密密麻麻的POM文件中看了半天,也没发现什么问题。我也没做多大改动啊,怎么就跑不起来了呢?
我想了下,问题会不会是依赖冲突导致的?
我去看看External Libraries

lib.png

卧槽,怎么会有两个jackson-core?版本还不一致!
终于找到原因了!
接下来,我修改了nacos的依赖:

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
    <!--排除此依赖对jackson-core的依赖-->
    <exclusions>
        <exclusion>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
        </exclusion>
    </exclusions>
</dependency>

改完后External Libraries里就只剩下一个jackson-core-2.13.1
刷新一下Maven,再次运行,终于Run起来了!

2022-09-05 00:26:59.919  INFO 20320 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2022-09-05 00:26:59.919  INFO 20320 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.56]
2022-09-05 00:26:59.980  INFO 20320 --- [  restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2022-09-05 00:26:59.981  INFO 20320 --- [  restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1282 ms
2022-09-05 00:27:01.624  INFO 20320 --- [  restartedMain] o.s.cloud.commons.util.InetUtils         : Cannot determine local hostname
2022-09-05 00:27:01.911  INFO 20320 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
2022-09-05 00:27:03.091  INFO 20320 --- [  restartedMain] o.s.cloud.commons.util.InetUtils         : Cannot determine local hostname
2022-09-05 00:27:03.113  INFO 20320 --- [  restartedMain] o.s.b.a.e.web.EndpointLinksResolver      : Exposing 1 endpoint(s) beneath base path '/actuator'
2022-09-05 00:27:03.404  INFO 20320 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8002 (http) with context path ''
2022-09-05 00:27:03.437  INFO 20320 --- [  restartedMain] c.a.c.n.registry.NacosServiceRegistry    : nacos registry, DEFAULT_GROUP file-manager 192.168.133.1:8002 register finished
2022-09-05 00:27:04.212  INFO 20320 --- [  restartedMain] cn.imcaoxuan.FileManagerApplication      : Started FileManagerApplication in 7.241 seconds (JVM running for 8.147)
2022-09-05 00:27:04.688  INFO 20320 --- [(1)-192.168.2.2] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2022-09-05 00:27:04.841  INFO 20320 --- [(1)-192.168.2.2] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2022-09-05 00:27:04.901  INFO 20320 --- [(3)-192.168.2.2] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-09-05 00:27:04.901  INFO 20320 --- [(3)-192.168.2.2] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2022-09-05 00:27:04.903  INFO 20320 --- [(3)-192.168.2.2] o.s.web.servlet.DispatcherServlet        : Completed initialization in 2 ms

Gradle 添加私有仓库

以Android Studio为例

  1. build.gradle(Project)中添加maven{...},如下所示:

    buildscript {
        repositories {
            maven {
                url "https://maven.imcaoxuan.cn:8443/repository/public/"
                credentials {
                    username = 'public'
                    password = 'public'
                }
            }
            google()
            mavenCentral()
        }
        dependencies {
            classpath 'com.android.tools.build:gradle:7.0.4'
    
            // NOTE: Do not place your application dependencies here; they belong
            // in the individual module build.gradle files
        }
    }
  2. settings.gradle(Project)中添加maven{...},如下所示:

    dependencyResolutionManagement {
        repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
        repositories {
            maven {
                url "https://maven.imcaoxuan.cn:8443/repository/public/"
                credentials {
                    username = 'public'
                    password = 'public'
                }
            }
            google()
            mavenCentral()
            jcenter() // Warning: this repository is going to shut down soon
        }
    }

    3.Sync now!

代码引用:org.apache.commons.codec.binary.Base32, org.apache.commons.codec.binary.Hex, TOTP(Johan Rydell, PortWise, Inc)

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.lang.reflect.UndeclaredThrowableException;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.util.Arrays;


public class TotpDemo {
    private static final int[] DIGITS_POWER
            // 0 1  2   3    4     5      6       7        8
            = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000};

    public static void main(String[] args) {
        // todo
        String secretKey = "";
        Base32 base32 = new Base32();
        byte[] bytes = base32.decode(secretKey.toUpperCase());
        // [-84, -88, -126, -19, 116, -72, -61, -58, 117, 53]
        String hexKey = Hex.encodeHexString(bytes);
        String hexTime = Long.toHexString(System.currentTimeMillis() / 30 / 1000);
        System.out.println(generateTOTP(hexKey, hexTime, "6"));
    }

    static class Hex {
        public static String encodeHexString(final byte[] data) {
            return new String(encodeHex(data));
        }

        public static char[] encodeHex(final byte[] data) {
            return encodeHex(data, true);
        }

        public static char[] encodeHex(final byte[] data, final boolean toLowerCase) {
            return encodeHex(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER);
        }

        protected static char[] encodeHex(final byte[] data, final char[] toDigits) {
            final int l = data.length;
            final char[] out = new char[l << 1];
            // two characters form the hex value.
            for (int i = 0, j = 0; i < l; i++) {
                out[j++] = toDigits[(0xF0 & data[i]) >>> 4];
                out[j++] = toDigits[0x0F & data[i]];
            }
            return out;
        }

        private static final char[] DIGITS_LOWER = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
                'e', 'f'};

        /**
         * Used to build output as Hex
         */
        private static final char[] DIGITS_UPPER = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
                'E', 'F'};
    }

    public static String generateTOTP(String key,
                                      String time,
                                      String returnDigits) {
        return generateTOTP(key, time, returnDigits, "HmacSHA1");
    }

    private static byte[] hmac_sha1(String crypto, byte[] keyBytes,
                                    byte[] text) {
        try {
            Mac hmac;
            hmac = Mac.getInstance(crypto);
            SecretKeySpec macKey =
                    new SecretKeySpec(keyBytes, "RAW");
            hmac.init(macKey);
            return hmac.doFinal(text);
        } catch (GeneralSecurityException gse) {
            throw new UndeclaredThrowableException(gse);
        }
    }

    private static byte[] hexStr2Bytes(String hex) {
        // Adding one byte to get the right conversion
        // values starting with "0" can be converted
        byte[] bArray = new BigInteger("10" + hex, 16).toByteArray();

        // Copy all the REAL bytes, not the "first"
        byte[] ret = new byte[bArray.length - 1];
        for (int i = 0; i < ret.length; i++)
            ret[i] = bArray[i + 1];
        return ret;
    }

    private static String generateTOTP(String key,
                                       String time,
                                       String returnDigits,
                                       String crypto) {
        int codeDigits = Integer.decode(returnDigits).intValue();
        String result;
        byte[] hash;

        // Using the counter
        // First 8 bytes are for the movingFactor
        // Complaint with base RFC 4226 (HOTP)
        while (time.length() < 16)
            time = "0" + time;

        // Get the HEX in a Byte[]
        byte[] msg = hexStr2Bytes(time);

        // Adding one byte to get the right conversion
        byte[] k = hexStr2Bytes(key);

        hash = hmac_sha1(crypto, k, msg);

        // put selected bytes into result int
        int offset = hash[hash.length - 1] & 0xf;

        int binary =
                ((hash[offset] & 0x7f) << 24) |
                        ((hash[offset + 1] & 0xff) << 16) |
                        ((hash[offset + 2] & 0xff) << 8) |
                        (hash[offset + 3] & 0xff);

        int otp = binary % DIGITS_POWER[codeDigits];

        result = Integer.toString(otp);
        while (result.length() < codeDigits) {
            result = "0" + result;
        }
        return result;
    }

    static abstract class BaseNCodec {
        static final int EOF = -1;
        protected final byte pad;
        protected static final int MASK_8BITS = 0xff;
        protected static final byte PAD_DEFAULT = '='; // Allow static access to default
        private final int unencodedBlockSize;

        /**
         * Number of bytes in each full block of encoded data, e.g. 3 for Base64 and 8 for Base32
         */
        private final int encodedBlockSize;
        protected final int lineLength;

        /**
         * Size of chunk separator. Not used unless {@link #lineLength} &gt; 0.
         */
        private final int chunkSeparatorLength;

        protected BaseNCodec(final int unencodedBlockSize, final int encodedBlockSize,
                             final int lineLength, final int chunkSeparatorLength, final byte pad) {
            this.unencodedBlockSize = unencodedBlockSize;
            this.encodedBlockSize = encodedBlockSize;
            final boolean useChunking = lineLength > 0 && chunkSeparatorLength > 0;
            this.lineLength = useChunking ? (lineLength / encodedBlockSize) * encodedBlockSize : 0;
            this.chunkSeparatorLength = chunkSeparatorLength;

            this.pad = pad;
        }

        public byte[] decode(final String pArray) {
            return decode(pArray.getBytes(StandardCharsets.UTF_8));
        }

        public byte[] decode(final byte[] pArray) {
            if (pArray == null || pArray.length == 0) {
                return pArray;
            }
            final Context context = new Context();
            decode(pArray, 0, pArray.length, context);
            decode(pArray, 0, EOF, context); // Notify decoder of EOF.
            final byte[] result = new byte[context.pos];
            readResults(result, 0, result.length, context);
            return result;
        }

        abstract void decode(byte[] pArray, int i, int length, Context context);

        int readResults(final byte[] b, final int bPos, final int bAvail, final Context context) {
            if (context.buffer != null) {
                final int len = Math.min(available(context), bAvail);
                System.arraycopy(context.buffer, context.readPos, b, bPos, len);
                context.readPos += len;
                if (context.readPos >= context.pos) {
                    context.buffer = null; // so hasData() will return false, and this method can return -1
                }
                return len;
            }
            return context.eof ? EOF : 0;
        }

        int available(final Context context) {  // package protected for access from I/O streams
            return context.buffer != null ? context.pos - context.readPos : 0;
        }

        protected byte[] ensureBufferSize(int size, Context context) {
            if (context.buffer == null) {
                context.buffer = new byte[this.getDefaultBufferSize()];
                context.pos = 0;
                context.readPos = 0;
            } else if (context.pos + size - context.buffer.length > 0) {
                return resizeBuffer(context, context.pos + size);
            }

            return context.buffer;
        }

        protected int getDefaultBufferSize() {
            return 8192;
        }

        private static byte[] resizeBuffer(Context context, int minCapacity) {
            int oldCapacity = context.buffer.length;
            int newCapacity = oldCapacity * 2;
            if (compareUnsigned(newCapacity, minCapacity) < 0) {
                newCapacity = minCapacity;
            }

            if (compareUnsigned(newCapacity, 2147483639) > 0) {
                newCapacity = createPositiveCapacity(minCapacity);
            }

            byte[] b = new byte[newCapacity];
            System.arraycopy(context.buffer, 0, b, 0, context.buffer.length);
            context.buffer = b;
            return b;
        }

        private static int compareUnsigned(int x, int y) {
            return Integer.compare(x + -2147483648, y + -2147483648);
        }

        private static int createPositiveCapacity(int minCapacity) {
            if (minCapacity < 0) {
                throw new OutOfMemoryError("Unable to allocate array size: " + ((long) minCapacity & 4294967295L));
            } else {
                return minCapacity > 2147483639 ? minCapacity : 2147483639;
            }
        }

        protected boolean containsAlphabetOrPad(final byte[] arrayOctet) {
            if (arrayOctet == null) {
                return false;
            }
            for (final byte element : arrayOctet) {
                if (pad == element || isInAlphabet(element)) {
                    return true;
                }
            }
            return false;
        }

        protected abstract boolean isInAlphabet(byte value);

        protected static boolean isWhiteSpace(final byte byteToCheck) {
            switch (byteToCheck) {
                case ' ':
                case '\n':
                case '\r':
                case '\t':
                    return true;
                default:
                    return false;
            }
        }

        static class Context {
            int ibitWorkArea;
            long lbitWorkArea;
            byte[] buffer;
            int pos;
            int readPos;
            boolean eof;
            int currentLinePos;
            int modulus;

            Context() {
            }

            public String toString() {
                return String.format("%s[buffer=%s, currentLinePos=%s, eof=%s, ibitWorkArea=%s, lbitWorkArea=%s, modulus=%s, pos=%s, readPos=%s]", this.getClass().getSimpleName(), Arrays.toString(this.buffer), this.currentLinePos, this.eof, this.ibitWorkArea, this.lbitWorkArea, this.modulus, this.pos, this.readPos);
            }
        }
    }

    static class Base32 extends TotpForXuandembp.BaseNCodec {
        private final int decodeSize;
        private final int encodeSize;
        private final byte[] decodeTable;
        private final byte[] encodeTable;
        private final byte[] lineSeparator;

        private static final int BITS_PER_ENCODED_BYTE = 5;
        private static final int BYTES_PER_ENCODED_BLOCK = 8;
        private static final int BYTES_PER_UNENCODED_BLOCK = 5;
        private static final long MASK_2BITS = 0x03L;
        private static final long MASK_7BITS = 0x7fL;
        /**
         * Mask used to extract 6 bits, used when decoding final trailing character.
         */
        private static final long MASK_6BITS = 0x3fL;
        /**
         * Mask used to extract 5 bits, used when encoding Base32 bytes
         */
        private static final int MASK_5BITS = 0x1f;
        /**
         * Mask used to extract 4 bits, used when decoding final trailing character.
         */
        private static final long MASK_4BITS = 0x0fL;
        /**
         * Mask used to extract 3 bits, used when decoding final trailing character.
         */
        private static final long MASK_3BITS = 0x07L;
        /** Mask used to extract 2 bits, used when decoding final trailing character. */
        /**
         * Mask used to extract 1 bits, used when decoding final trailing character.
         */
        private static final long MASK_1BITS = 0x01L;

        public Base32() {
            this(false);
        }

        public Base32(final boolean useHex) {
            this(0, null, useHex, PAD_DEFAULT);
        }

        public Base32(final int lineLength, final byte[] lineSeparator, final boolean useHex, final byte pad) {
            super(BYTES_PER_UNENCODED_BLOCK, BYTES_PER_ENCODED_BLOCK, lineLength,
                    lineSeparator == null ? 0 : lineSeparator.length, pad);
            if (useHex) {
                this.encodeTable = HEX_ENCODE_TABLE;
                this.decodeTable = HEX_DECODE_TABLE;
            } else {
                this.encodeTable = ENCODE_TABLE;
                this.decodeTable = DECODE_TABLE;
            }
            if (lineLength > 0) {
                if (lineSeparator == null) {
                    throw new IllegalArgumentException("lineLength " + lineLength + " > 0, but lineSeparator is null");
                }
                // Must be done after initializing the tables
                if (containsAlphabetOrPad(lineSeparator)) {
                    final String sep = new String(lineSeparator, StandardCharsets.UTF_8);
                    throw new IllegalArgumentException("lineSeparator must not contain Base32 characters: [" + sep + "]");
                }
                this.encodeSize = BYTES_PER_ENCODED_BLOCK + lineSeparator.length;
                this.lineSeparator = new byte[lineSeparator.length];
                System.arraycopy(lineSeparator, 0, this.lineSeparator, 0, lineSeparator.length);
            } else {
                this.encodeSize = BYTES_PER_ENCODED_BLOCK;
                this.lineSeparator = null;
            }
            this.decodeSize = this.encodeSize - 1;

            if (isInAlphabet(pad) || isWhiteSpace(pad)) {
                throw new IllegalArgumentException("pad must not be in alphabet or whitespace");
            }
        }

        private static final byte[] HEX_DECODE_TABLE = {
                //  0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
                -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 00-0f
                -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 10-1f
                -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 20-2f
                0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, // 30-3f 2-7
                -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, // 40-4f A-O
                25, 26, 27, 28, 29, 30, 31,                                     // 50-56 P-V
                -1, -1, -1, -1, -1, -1, -1, -1, -1, // 57-5f Z-_
                -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, // 60-6f `-o
                25, 26, 27, 28, 29, 30, 31                                      // 70-76 p-v
        };

        /**
         * This array is a lookup table that translates 5-bit positive integer index values into their
         * "Base32 Hex Alphabet" equivalents as specified in Table 4 of RFC 4648.
         */
        private static final byte[] HEX_ENCODE_TABLE = {
                '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
                'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
        };
        private static final byte[] DECODE_TABLE = {
                //  0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
                -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 00-0f
                -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 10-1f
                -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 20-2f
                -1, -1, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1, -1, -1, -1, -1, // 30-3f 2-7
                -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, // 40-4f A-O
                15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,                     // 50-5a P-Z
                -1, -1, -1, -1, -1, // 5b - 5f
                -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, // 60 - 6f a-o
                15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,                     // 70 - 7a p-z/**/
        };

        /**
         * This array is a lookup table that translates 5-bit positive integer index values into their "Base32 Alphabet"
         * equivalents as specified in Table 3 of RFC 4648.
         */
        private static final byte[] ENCODE_TABLE = {
                'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
                'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
                '2', '3', '4', '5', '6', '7',
        };

        private static void validateCharacter(final long emptyBitsMask, final Context context) {
            // Use the long bit work area
            if ((context.lbitWorkArea & emptyBitsMask) != 0) {
                throw new IllegalArgumentException(
                        "Last encoded character (before the paddings if any) is a valid base 32 alphabet but not a possible value. " +
                                "Expected the discarded bits to be zero.");
            }
        }

        void decode(final byte[] input, int inPos, final int inAvail, final Context context) {
            // package protected for access from I/O streams

            if (context.eof) {
                return;
            }
            if (inAvail < 0) {
                context.eof = true;
            }
            for (int i = 0; i < inAvail; i++) {
                final byte b = input[inPos++];
                if (b == pad) {
                    // We're done.
                    context.eof = true;
                    break;
                }
                final byte[] buffer = ensureBufferSize(decodeSize, context);
                if (b >= 0 && b < this.decodeTable.length) {
                    final int result = this.decodeTable[b];
                    if (result >= 0) {
                        context.modulus = (context.modulus + 1) % BYTES_PER_ENCODED_BLOCK;
                        // collect decoded bytes
                        context.lbitWorkArea = (context.lbitWorkArea << BITS_PER_ENCODED_BYTE) + result;
                        if (context.modulus == 0) { // we can output the 5 bytes
                            buffer[context.pos++] = (byte) ((context.lbitWorkArea >> 32) & MASK_8BITS);
                            buffer[context.pos++] = (byte) ((context.lbitWorkArea >> 24) & MASK_8BITS);
                            buffer[context.pos++] = (byte) ((context.lbitWorkArea >> 16) & MASK_8BITS);
                            buffer[context.pos++] = (byte) ((context.lbitWorkArea >> 8) & MASK_8BITS);
                            buffer[context.pos++] = (byte) (context.lbitWorkArea & MASK_8BITS);
                        }
                    }
                }
            }

            // Two forms of EOF as far as Base32 decoder is concerned: actual
            // EOF (-1) and first time '=' character is encountered in stream.
            // This approach makes the '=' padding characters completely optional.
            if (context.eof && context.modulus >= 2) { // if modulus < 2, nothing to do
                final byte[] buffer = ensureBufferSize(decodeSize, context);

                //  we ignore partial bytes, i.e. only multiples of 8 count
                switch (context.modulus) {
                    case 2: // 10 bits, drop 2 and output one byte
                        validateCharacter(MASK_2BITS, context);
                        buffer[context.pos++] = (byte) ((context.lbitWorkArea >> 2) & MASK_8BITS);
                        break;
                    case 3: // 15 bits, drop 7 and output 1 byte
                        validateCharacter(MASK_7BITS, context);
                        buffer[context.pos++] = (byte) ((context.lbitWorkArea >> 7) & MASK_8BITS);
                        break;
                    case 4: // 20 bits = 2*8 + 4
                        validateCharacter(MASK_4BITS, context);
                        context.lbitWorkArea = context.lbitWorkArea >> 4; // drop 4 bits
                        buffer[context.pos++] = (byte) ((context.lbitWorkArea >> 8) & MASK_8BITS);
                        buffer[context.pos++] = (byte) ((context.lbitWorkArea) & MASK_8BITS);
                        break;
                    case 5: // 25bits = 3*8 + 1
                        validateCharacter(MASK_1BITS, context);
                        context.lbitWorkArea = context.lbitWorkArea >> 1;
                        buffer[context.pos++] = (byte) ((context.lbitWorkArea >> 16) & MASK_8BITS);
                        buffer[context.pos++] = (byte) ((context.lbitWorkArea >> 8) & MASK_8BITS);
                        buffer[context.pos++] = (byte) ((context.lbitWorkArea) & MASK_8BITS);
                        break;
                    case 6: // 30bits = 3*8 + 6
                        validateCharacter(MASK_6BITS, context);
                        context.lbitWorkArea = context.lbitWorkArea >> 6;
                        buffer[context.pos++] = (byte) ((context.lbitWorkArea >> 16) & MASK_8BITS);
                        buffer[context.pos++] = (byte) ((context.lbitWorkArea >> 8) & MASK_8BITS);
                        buffer[context.pos++] = (byte) ((context.lbitWorkArea) & MASK_8BITS);
                        break;
                    case 7: // 35 = 4*8 +3
                        validateCharacter(MASK_3BITS, context);
                        context.lbitWorkArea = context.lbitWorkArea >> 3;
                        buffer[context.pos++] = (byte) ((context.lbitWorkArea >> 24) & MASK_8BITS);
                        buffer[context.pos++] = (byte) ((context.lbitWorkArea >> 16) & MASK_8BITS);
                        buffer[context.pos++] = (byte) ((context.lbitWorkArea >> 8) & MASK_8BITS);
                        buffer[context.pos++] = (byte) ((context.lbitWorkArea) & MASK_8BITS);
                        break;
                    default:
                        // modulus can be 0-7, and we excluded 0,1 already
                        throw new IllegalStateException("Impossible modulus " + context.modulus);
                }
            }
        }

        @Override
        protected boolean isInAlphabet(byte octet) {
            return octet >= 0 && octet < decodeTable.length && decodeTable[octet] != -1;
        }
    }
}

今天在解析一个5M的文本文件时,耗时两分多钟,找了半天才发现原因是使用String += s的方式拼接字符串导致的。
123-1.png

换成StringBuilder后速度提升了4个数量级!123-2.png

至于原因,大家应该都懂,我就不再赘述了。
基础不能忘!!!
基础不能忘!!!
基础不能忘!!!