编程知识 cdmana.com

Exception resolution -- when getting spring context appplicationcontextaware, ApplicationContext is null

Because dynamic access is used in the project Bean The way , So consider implementation AppplicationContextAware How to get Spring Context .

But recently, servers often appear SpringUitl.getBean The problem of null pointer ., And not often The code is as follows :

package com.jingchen.ccsp.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringUtil implements ApplicationContextAware{
	
	private static ApplicationContext applicationContext;

	@Override
	public void setApplicationContext(ApplicationContext arg0) throws BeansException {
		
		if(applicationContext == null) applicationContext = arg0;
		
	}
	
	public static Object getBean(String name) {
		
		return applicationContext.getBean(name);
		
	} 

}

Look at the realization , No problem , I also checked it on the Internet , be supposed to Inject... In the form of annotations SpringUtil, In order to jar Way to start SpringBoot Project then SpringUtil Class must be placed in the boot class sibling package directory .

Otherwise, sometimes you will get something for null

But I don't think it's friendly to change like this , So just put SpringUtil From the way of annotation to xml The way the statement is made . And set the delay loading to false

<bean id="springUtil" class="com.jingchen.ccsp.util.SpringUtil" scope="singleton" lazy-init="false" />

Repackage to start , Project testing is OK !

I know someone will ask me , Yes? SpringBoot To configure spring Of xml Loading . As follows :

package com.jingchen.ccsp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;

@Configuration
@ImportResource(locations = {"classpath:config/Entrance.xml","classpath:spring/application-spring.xml"})
@SpringBootApplication
public class CmepApplication {

	public static void main(String[] args) {

		try {
			SpringApplication.run(CmepApplication.class, args);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}

Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .

版权声明
本文为[The blank of writing memory]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201224104023996q.html

Scroll to Top