取得Spring配置文件中的Bean对象的通用方法
2013-02-21 22:20
465 查看
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; /** * 以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候中取出ApplicaitonContext. * */ public class SpringContextHolder implements ApplicationContextAware { private static ApplicationContext applicationContext; /** * 实现ApplicationContextAware接口的context注入函数, 将其存入静态变量. */ public void setApplicationContext(ApplicationContext applicationContext) { SpringContextHolder.applicationContext = applicationContext; // NOSONAR } /** * 取得存储在静态变量中的ApplicationContext. */ public static ApplicationContext getApplicationContext() { checkApplicationContext(); return applicationContext; } /** * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型. */ @SuppressWarnings("unchecked") public static <T> T getBean(String name) { checkApplicationContext(); return (T) applicationContext.getBean(name); } /** * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型. */ @SuppressWarnings("unchecked") public static <T> T getBean(Class<T> clazz) { checkApplicationContext(); return (T) applicationContext.getBeansOfType(clazz); } /** * 清除applicationContext静态变量. */ public static void cleanApplicationContext() { applicationContext = null; } private static void checkApplicationContext() { if (applicationContext == null) { throw new IllegalStateException("applicaitonContext未注入,请在applicationContext.xml中定义SpringContextHolder"); } } }
用于持有ApplicationContext,可以使用SpringContextHolder.getBean('xxxx')的静态方法得到spring bean对象
原文地址:http://elf8848.iteye.com/blog/875830
相关文章推荐
- [java][spring]取得通过配置文件和注解注入的bean、取得当前数据库连接、取得ApplicationContext的方法
- [java][spring]取得通过配置文件和注解注入的bean、取得当前数据库连接、取得ApplicationContext的方法
- spring 实例化定义在xml配置文件中的bean的三种方法?
- Spring中使用事务搭建转账环境方法二 相对简便的注解方法 ——配置文件注入对象属性需要setter方法 注解方法,不需要生成setter方法
- 使用dom4j:读取spring配置文件,实例化bean对象并注入依赖对象
- spring在配置文件中bean对象创建的三种方式
- 使用dom4j:读取spring配置文件,实例化bean对象并注入依赖对象
- Spring配置文件外部化配置及.properties的通用方法
- [java][spring]取得通过配置文件和注解注入的bean、取得当前数据库连接、取得Appli
- Spring配置文件中使用ref local与ref bean的区别. 在ApplicationResources.properties文件中,使用<ref bean>与<ref local>方法如下
- java 获取spring配置文件中bean 对象
- Spring读取xml配置文件并加载bean对象
- Spring配置文件中使用ref local与ref bean的区别. 在ApplicationResources.properties文件中,使用<ref bean>与<ref local>方法如下
- Spring配置文件中使用ref local与ref bean的区别. 在ApplicationResources.properties文件中,使用<ref bean>与<ref local>方法如下
- Spring读取配置文件中的bean与注入后的bean的方法
- spring学习教程7-spring容器创建bean对象的方式以及如何处理多个spring配置文件
- 在Maven项目中加载spring中的bean的配置xml文件会提示找不到解决方法
- spring-01 spring的bean管理(使用配置文件方式创建对象 附代码)
- Spring中使用事务搭建转账环境方法二 相对简便的注解方法 ——配置文件注入对象属性需要setter方法 注解方法,不需要生成setter方法
- Spring中c3p0连接池的配置 及JdbcTemplate的使用 通过XML配置文件注入各种需要对象的操作 来完成数据库添加Add()方法