今天遇到一个问题:
通过ApplicationContext获取spring容器中的bean时,报ApplicationContext为null,代码如下:
public class ServiceBeanUtils implements ApplicationContextAware { protected static ApplicationContext staticContext; protected ServiceBeanUtils() { } public void setApplicationContext(ApplicationContext context) throws BeansException { staticContext = context; } public static Object getBean(String strBeanName) { try { return staticContext.getBean(strBeanName); } catch (Exception e) { e.printStackTrace(); } return null; } public static IBaseService getServiceBean(String strBeanName){ return (IBaseService)getBean(strBeanName); } }
查找原因:xml文件的加载顺序不正确,ServiceBeanUtils还没有加载, ApplicationContext还没有初始化,而服务启动时就有个类通过调用ApplicationContext去取bean进行初始化了
解决方案:先加载ServiceBeanUtils类,去初始化ApplicationContext,然后再加载要调用ApplicationContext的类去初始化此类
如下:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <bean class="com.hw.hwsafe.platform.util.ServiceBeanUtils" /> <bean id="loginLogService" class="com.hw.hwsafe.platform.service.impl.LoginLogServiceImpl"/> </beans>
相关推荐
Spring配置文件ApplicationContext,内容齐全,有需要的可以下载。
Spring Web MVC开发 xml配置文件格式,无bean之类 Spring Web MVC开发配置文件 applicationContext
《Spring的数据源配置文件模板》applicationContext.zip
Spring中ApplicationContext加载机制
spring2.5的applicationContext配置文件.
spring配置文件详解,Spring的applicationContext.xml文件代码:
Spring框架配置文件applicationContext.xml
<description>Spring公共配置文件 <!-- mes 的數據庫 --> <property name="driverClass" value="oracle.jdbc.driver.OracleDriver"/> ...
初学Spring的小伙伴,还在为找不到主配置文件而着急吗,该配置文件是基于Spring4.10版本的,不用再自己到官网页面上到处找了,分享给大家,也希望大家别再像我一样因为这个坑耽误了大半天的时间,如果要自己配置也...
Spring配置文件是一个或多个标准的XML文档,applicationContext.xml是Spring的默认配置文件,当容器启动时找不到指定的配置文档时,将会尝试加载这个默认的配置文件。 下面列举的是一份比较完整的配置文件模板,...
spring 所有包 配置文件 包括 applicationContext.xml
ssh框架事务管理applicationContext.xml配置文件
spring约束文件头文件ApplicationContext.xml的头文件
Spring Boot技术知识点:如何读取不同路径里的applicationContext.xml配置文件4
Spring中ApplicationContext和beanfactory区别.rar
本篇文章主要介绍了详解spring applicationContext.xml 配置文件 ,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
在本篇文章里我们给各位整理的是关于Spring主配置文件(applicationContext.xml) 导入约束的相关知识点内容,需要参考下。
spring定时器。这里有需要的包和applicationContext.xml配置文件
Spring Boot技术知识点:如何读取不同路径里的applicationContext.xml配置文件6