SpringBoot项目中遇到的异常

问题:

SpringBoot项目中集成了阿里开源Druid数据源,本地开发环境直接启动SpringBoot应用(SpringApplication.run方法),启动成功,由于正式应用是部署在服务器已有的Tomcat环境中,经过改造将SpringBoot项目打成ROOT.war包后,部署到服务器上,启动应用程序时,报错了,错误信息如下所示:

15:13:34.616 repair [localhost-startStop-1] DEBUG o.springframework.jndi.JndiTemplate - Looking up JNDI object with name [java:comp/env/logging.level]
15:13:34.607 repair [localhost-startStop-1] DEBUG o.s.jndi.JndiPropertySource - JNDI lookup for name [logging.group] threw NamingException with message: Name [logging.group] is not bound in this Context. Unable to find [logging.group].. Returning null.
15:13:34.606 repair [localhost-startStop-1] DEBUG o.springframework.jndi.JndiTemplate - Looking up JNDI object with name [logging.group]
15:13:34.606 repair [localhost-startStop-1] DEBUG o.s.jndi.JndiLocatorDelegate - Converted JNDI name [java:comp/env/logging.group] not found - trying original name [logging.group]. javax.naming.NameNotFoundException: Name [logging.group] is not bound in this Context. Unable to find [logging.group].
15:13:34.580 repair [background-preinit] DEBUG o.h.v.m.ResourceBundleMessageInterpolator - Loaded expression factory via original TCCL
15:13:34.599 repair [localhost-startStop-1] DEBUG o.springframework.jndi.JndiTemplate - Looking up JNDI object with name [java:comp/env/logging.group]
15:13:34.578 repair [localhost-startStop-1] DEBUG o.s.jndi.JndiPropertySource - JNDI lookup for name [logging.group] threw NamingException with message: Name [logging.group] is not bound in this Context. Unable to find [logging.group].. Returning null.
15:13:34.577 repair [localhost-startStop-1] DEBUG o.springframework.jndi.JndiTemplate - Looking up JNDI object with name [logging.group]
15:13:34.577 repair [localhost-startStop-1] DEBUG o.s.jndi.JndiLocatorDelegate - Converted JNDI name [java:comp/env/logging.group] not found - trying original name [logging.group]. javax.naming.NameNotFoundException: Name [logging.group] is not bound in this Context. Unable to find [logging.group].
15:13:34.548 repair [localhost-startStop-1] DEBUG o.springframework.jndi.JndiTemplate - Looking up JNDI object with name [java:comp/env/logging.group]
    ... 74 common frames omitted
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:136)
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:307)
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:363)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at cn.demo.repair.service.impl.VpServiceImpl.init(VpServiceImpl.java:42)
    at java.util.Properties.load(Properties.java:341)
    at java.util.Properties.load0(Properties.java:353)
    at java.util.Properties$LineReader.readLine(Properties.java:434)
Caused by: java.lang.NullPointerException: null
    ... 61 common frames omitted
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1166)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1239)
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:273)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory$$Lambda$120/684584821.getObject(Unknown Source)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:576)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1737)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:419)
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:139)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'VpServiceImpl': Invocation of init method failed; nested exception is java.lang.NullPointerException
    ... 47 common frames omitted
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1166)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1239)
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:273)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory$$Lambda$120/684584821.getObject(Unknown Source)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:575)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1378)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'approvalServiceImpl': Unsatisfied dependency expressed through field 'vpService'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'VpServiceImpl': Invocation of init method failed; nested exception is java.lang.NullPointerException
    ... 33 common frames omitted
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1166)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1239)
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:273)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory$$Lambda$120/684584821.getObject(Unknown Source)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:575)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1378)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'repairServiceImpl': Unsatisfied dependency expressed through field 'approvalService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'approvalServiceImpl': Unsatisfied dependency expressed through field 'vpService'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'VpServiceImpl': Invocation of init method failed; nested exception is java.lang.NullPointerException
    at java.lang.Thread.run(Thread.java:745)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1823)
    at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:952)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:700)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:724)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5178)
    at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:171)
    at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.onStartup(SpringBootServletInitializer.java:91)
    at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.createRootApplicationContext(SpringBootServletInitializer.java:137)
    at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.run(SpringBootServletInitializer.java:157)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:316)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775)
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:546)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:863)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:846)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory$$Lambda$120/684584821.getObject(Unknown Source)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:575)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1378)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596)
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'repairController': Unsatisfied dependency expressed through field 'repairService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'repairServiceImpl': Unsatisfied dependency expressed through field 'approvalService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'approvalServiceImpl': Unsatisfied dependency expressed through field 'vpService'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'VpServiceImpl': Invocation of init method failed; nested exception is java.lang.NullPointerException
15:07:53.610 repair [localhost-startStop-1] ERROR o.s.boot.SpringApplication - Application run failed
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.

15:07:53.586 repair [localhost-startStop-1] INFO  o.s.b.a.l.ConditionEvaluationReportLoggingListener - 
15:07:53.536 repair [localhost-startStop-1] INFO  c.alibaba.druid.pool.DruidDataSource - {dataSource-1} closed
15:07:53.258 repair [localhost-startStop-1] WARN  o.s.b.w.s.c.AnnotationConfigServletWebServerApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'repairController': Unsatisfied dependency expressed through field 'repairService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'repairServiceImpl': Unsatisfied dependency expressed through field 'approvalService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'approvalServiceImpl': Unsatisfied dependency expressed through field 'vpService'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'VpServiceImpl': Invocation of init method failed; nested exception is java.lang.NullPointerException
15:07:37.645 repair [localhost-startStop-1] INFO  c.alibaba.druid.pool.DruidDataSource - {dataSource-1} inited
15:07:28.073 repair [localhost-startStop-1] INFO  c.a.d.s.b.a.DruidDataSourceAutoConfigure - Init DruidDataSource
15:07:25.620 repair [localhost-startStop-1] INFO  o.s.b.w.s.FilterRegistrationBean - Mapping filter: 'webStatFilter' to urls: [/*]
15:07:25.619 repair [localhost-startStop-1] INFO  o.s.b.w.s.FilterRegistrationBean - Mapping filter: 'requestContextFilter' to: [/*]
15:07:25.619 repair [localhost-startStop-1] INFO  o.s.b.w.s.FilterRegistrationBean - Mapping filter: 'formContentFilter' to: [/*]
15:07:25.618 repair [localhost-startStop-1] INFO  o.s.b.w.s.FilterRegistrationBean - Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
15:07:25.618 repair [localhost-startStop-1] INFO  o.s.b.w.s.FilterRegistrationBean - Mapping filter: 'errorPageFilter' to: [/*]
15:07:25.617 repair [localhost-startStop-1] INFO  o.s.b.w.s.FilterRegistrationBean - Mapping filter: 'characterEncodingFilter' to: [/*]
15:07:25.570 repair [localhost-startStop-1] INFO  o.s.b.w.s.ServletRegistrationBean - Servlet statViewServlet mapped to [/druid/*]
15:07:25.568 repair [localhost-startStop-1] INFO  o.s.b.w.s.ServletRegistrationBean - Servlet dispatcherServlet mapped to [/]
15:07:23.151 repair [localhost-startStop-1] INFO  o.s.web.context.ContextLoader - Root WebApplicationContext: initialization completed in 16648 ms
15:07:22.043 repair [localhost-startStop-1] INFO  o.s.c.s.PostProcessorRegistrationDelegate$BeanPostProcessorChecker - Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$e7ee3861] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
15:07:17.690 repair [localhost-startStop-1] INFO  o.s.d.r.c.RepositoryConfigurationDelegate - Finished Spring Data repository scanning in 421ms. Found 0 repository interfaces.
15:07:17.185 repair [localhost-startStop-1] INFO  o.s.d.r.c.RepositoryConfigurationDelegate - Bootstrapping Spring Data repositories in DEFAULT mode.
15:07:17.154 repair [localhost-startStop-1] INFO  o.s.d.r.c.RepositoryConfigurationDelegate - Multiple Spring Data modules found, entering strict repository configuration mode!
15:07:06.257 repair [localhost-startStop-1] INFO  cn.demo.repair.RepairApplication - The following profiles are active: dev
15:07:06.256 repair [localhost-startStop-1] DEBUG cn.demo.repair.RepairApplication - Running with Spring Boot v2.1.0.RELEASE, Spring v5.1.2.RELEASE
15:07:06.235 repair [localhost-startStop-1] INFO  cn.demo.repair.RepairApplication - Starting RepairApplication v0.0.1-SNAPSHOT on 10.40.20.119 with PID 102172 (/home/work/data/www/demo-repair/ROOT/WEB-INF/classes started by work in /home/work)

 :: Spring Boot ::        (v2.1.0.RELEASE)
 =========|_|==============|___/=/_/_/_/
  '  |____| .__|_| |_|_| |_\__, | / / / /
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
  .   ____          _            __ _ _

分析:

分析报错信息,看到DruidDataSource初始化后,出现WARN信息,依赖生成bin的时候(最终生成VpServiceImpl的bin时)出现了空指针异常,如下异常信息:

15:07:53.536 repair [localhost-startStop-1] INFO  c.alibaba.druid.pool.DruidDataSource - {dataSource-1} closed
15:07:53.258 repair [localhost-startStop-1] WARN  o.s.b.w.s.c.AnnotationConfigServletWebServerApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'repairController': Unsatisfied dependency expressed through field 'repairService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'repairServiceImpl': Unsatisfied dependency expressed through field 'approvalService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'approvalServiceImpl': Unsatisfied dependency expressed through field 'vpService'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'VpServiceImpl': Invocation of init method failed; nested exception is java.lang.NullPointerException
15:07:37.645 repair [localhost-startStop-1] INFO  c.alibaba.druid.pool.DruidDataSource - {dataSource-1} inited

刚开始以为是SpringBoot集成DruidDataSource出了问题,各种查各种找,没有解决。

在网上搜能引起SpringBoot启动出现以下报错的原因,然也没有解决。

15:07:53.610 repair [localhost-startStop-1] ERROR o.s.boot.SpringApplication - Application run failed Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.

异常意思是:应用程序运行启动ApplicationContext失败,要显示条件报告,请在“debug”模式下重新运行应用程序。

此时觉得可能是出发的方向错了,所以再次回过头来,仔细分析异常堆栈信息,看到两行:

at cn.demo.repair.service.impl.VpServiceImpl.init(VpServiceImpl.java:42)
at java.util.Properties.load(Properties.java:341)

觉得应该是自己程序中:在VpServiceImpl类初始化方法init中,Properties对象load文件时抛出了空指针异常。有了明确方向,开始研究出现问题的代码。

较详细的异常信息摘录:

15:13:34.548 repair [localhost-startStop-1] DEBUG o.springframework.jndi.JndiTemplate - Looking up JNDI object with name [java:comp/env/logging.group]
    ... 74 common frames omitted
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:136)
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:307)
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:363)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at cn.demo.repair.service.impl.VpServiceImpl.init(VpServiceImpl.java:42)
    at java.util.Properties.load(Properties.java:341)
    at java.util.Properties.load0(Properties.java:353)
    at java.util.Properties$LineReader.readLine(Properties.java:434)
Caused by: java.lang.NullPointerException: null
    ... 61 common frames omitted

结果发现直接用SpringBoot自带的SpringApplication.run方法启动应用程序,VpServiceImpl类的init方法不报错,而且应用程序启动成功,跑业务也正常,但是改造打成ROOT.war包后,部署到服务器的Tomcat上,就报错了,应用程序也启动失败。

哎呀,脑仁疼,怎么办,怎么办,怎么办......

脑子里一闪现,可能是打ROOT.war包出的问题,不对,不能再跑偏(因为之前版本部署ROOT.war没问题),立即弄死这个想法。

正确的招:分析代码,添加详细的日志打印。

然后问题的根源逐渐浮出水面,直接看代码:

@Service
@Slf4j
public class VpServiceImpl implements VpService{

    @Value("${vp.path}")
    private String vpPath;

    /**
     * VP列表
     */
    private Set<String> vpSet;

    /**
     * Properties文件
     */
    private Properties vpProperties;

    /**
     * 初始化VP列表
     */
    @PostConstruct
    private void init() {
        vpProperties = new Properties();
        try {
            vpProperties.load(ClassLoader.getSystemResourceAsStream(vpPath));
        } catch (IOException e) {
            log.error("Failed to load the vp.properties file. vpPath = " + vpPath + ", IOException : " + e);
        }
        vpSet = vpProperties.stringPropertyNames();
    }

    @Override
    public Set<String> getVpSet() {
        return vpSet;
    }

    @Override
    public String getVpLeader(String username) {
        if (!vpSet.contains(username)) {
            return null;
        }
        String vpLeader = vpProperties.getProperty(username);
        return StringUtils.isEmpty(vpLeader) ? vpProperties.getProperty("vpLeader", "xxx") : vpLeader;
    }

    @Override
    public void setVpSet(Set<String> vpSet) {
        this.vpSet = vpSet;
    }

    @Override
    public boolean addVp(String... vp) {
        if (vpSet == null) {
            vpSet = new HashSet<>();
        }
        return vpSet.addAll(Arrays.asList(vp));
    }

    @Override
    public boolean addVp(List<String> vpList) {
        if (vpSet == null) {
            vpSet = new HashSet<>();
        }
        return vpSet.addAll(vpList);
    }
}

vp.path在application.yml文件中的配置如下:

vp:
  path: vp.properties

vp.properties在SpringBoot工程的resources目录下:

vp.properties文件

代码中Properties对象vpProperties转载InputStream输入流,而InputStream输入流是通过获取vp.properties文件资源转换而来的,这里是有问题的,ClassLoader.getSystemResourceAsStream(vpPath)在实际线上服务器环境中找不到vp.properties文件,所以报了空指针异常,导致线上应用程序启动失败。

解决方法:

代码修改:

@PostConstruct
private void init() {
    vpProperties = new Properties();
    try {
        vpProperties.load(VpServiceImpl.class.getClassLoader().getResourceAsStream(vpPath));
    } catch (Exception e) {
        log.error("Failed to load the vp.properties file. vpPath = " + vpPath + ", Exception : " + e);
    }
    vpSet = vpProperties.stringPropertyNames();
}

修改点:

  • vpProperties.load(ClassLoader.getSystemResourceAsStream(vpPath));改为vpProperties.load(VpServiceImpl.class.getClassLoader().getResourceAsStream(vpPath));
  • catch所有异常,不会导致应用程序启动失败。

总结:

程序报错了,不要瞎考虑,乱认为,一定要仔细研究异常栈信息,仔细研究异常栈信息,仔细研究异常栈信息(重要的事说三遍)。

知识扩展:

写累了,随后再扩展吧。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 205,132评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,802评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,566评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,858评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,867评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,695评论 1 282
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,064评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,705评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 42,915评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,677评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,796评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,432评论 4 322
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,041评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,992评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,223评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,185评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,535评论 2 343

推荐阅读更多精彩内容