解决Spring静态代码块加载@Autowired方法java.lang.NullPointerException问题
由于Static 静态代码块加载时,Spring的对象还未产生,导致初始化失败
java.lang.ExceptionInInitializerError
Caused by: java.lang.NullPointerException: null
at com.ityemu.manage.bi.controller.TestController.(TestController.java:25) ~[classes/:na]
… 30 common frames omitted
解决方案,有以下两种途径:
方案一:
1.实现BeanFactoryPostProcessor 接口
@Component
public class SpringContextUtil implements BeanFactoryPostProcessor {
/** Spring应用上下文环境 */
private static ConfigurableListableBeanFactory beanFactory;
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
SpringContextUtil.beanFactory = configurableListableBeanFactory;
}
/**
* 获取对象
*
* @param clazz
* @return Object 一个以所给名字注册的bean的实例
* @throws org.springframework.beans.BeansException
*
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(Class clazz) throws BeansException
{
return (T) beanFactory.getBean(clazz.getName());
}
2.在引用Service类 上使用全路径类名
否则启动报错,找不到类
A component required a bean named ‘com.ityemu.manage.bi.service.CaCheService’ that could not be found.
或者
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named ‘com.ityemu.manage.bi.service.CaCheService’ available
3.在需要引用的地方使用
private static CaCheService cacheservice =(CaCheService) SpringContextUtil.getBean(CaCheService.class);
注: 此时不需要使用@Autowired 或者@Resource 注解标签
方案二:
1.继承HttpServlet
@WebServlet(loadOnStartup=2000,urlPatterns = "/")
public class SpringTool extends HttpServlet {
private static ApplicationContext applicationContext ; //Spring上下文
private static SpringTool instance ;
public void init() throws ServletException {
SpringTool.initInstance(this.getServletContext());
}
public static SpringTool initInstance(ServletContext servletContext){
if(instance == null){
instance = new SpringTool() ;
applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
}
return instance ;
}
public static Object getBean(Class clazz){
Object object = null ;
try{
object = applicationContext.getBean(clazz.getName()) ;
}catch(Exception e){
e.printStackTrace();
}
return object ;
}
}
注:loadOnStartup 启动的优先级
2.在引用Service类 上使用全路径类名
3.在需要引用的地方使用
private static CaCheService cacheservice =(CaCheService) SpringTool.getBean(CaCheService.class);
注: 此时不需要使用@Autowired 或者@Resource 注解标签