问题:
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 TCCL15: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.NullPointerException15:07:53.610 repair [localhost-startStop-1] ERROR o.s.boot.SpringApplication - Application run failedError 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} closed15: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.NullPointerException15:07:37.645 repair [localhost-startStop-1] INFO c.alibaba.druid.pool.DruidDataSource - {dataSource-1} inited15:07:28.073 repair [localhost-startStop-1] INFO c.a.d.s.b.a.DruidDataSourceAutoConfigure - Init DruidDataSource15: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 ms15: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: dev15:07:06.256 repair [localhost-startStop-1] DEBUG cn.demo.repair.RepairApplication - Running with Spring Boot v2.1.0.RELEASE, Spring v5.1.2.RELEASE15: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} closed15: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.NullPointerException15: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@Slf4jpublic class VpServiceImpl implements VpService{ @Value("${vp.path}") private String vpPath; /** * VP列表 */ private SetvpSet; /** * 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 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 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 vpList) { if (vpSet == null) { vpSet = new HashSet<>(); } return vpSet.addAll(vpList); }}复制代码
vp.path在application.yml文件中的配置如下:
vp: path: vp.properties复制代码
vp.properties在SpringBoot工程的resources目录下:
代码中Properties对象vpProperties转载InputStream输入流,而InputStream输入流是通过获取vp.properties文件资源转换而来的,这里是有问题的,ClassLoader.getSystemResourceAsStream(vpPath)
在实际线上服务器环境中找不到vp.properties文件,所以报了空指针异常,导致线上应用程序启动失败。
解决方法:
代码修改:
@PostConstructprivate 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所有异常,不会导致应用程序启动失败。
总结:
程序报错了,不要瞎考虑,乱认为,一定要仔细研究异常栈信息,仔细研究异常栈信息,仔细研究异常栈信息(重要的事说三遍)。
知识扩展:
写累了,随后再扩展吧。