工作中需要对一个原本加载属性文件的工具类修改成对数据库的操作当然,ado层已经写好,但是需要从Spring中获取bean,然而,工具类并没有交给Spring来管理,所以需要通过方法获取所需要的bean。于是整理了Spring获取bean的几种方法。

  一. 在初始化时保存ApplicationContext对象

    ApplicationContext ac = new FileSystemXmlApplicationContext("classpath:beans.xml");
ac.getBean("beanId");

 说明:这种方式适用于采用Spring框架的独立应用程序,需要程序通过配置文件手工初始化Spring的情况。不难理解对于通过web.xml配置启动的Spring来说也一定是里面实现了此方法。

二. 通过Spring提供的工具类获取ApplicationContext对象

    ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc);
ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(ServletContext sc);
ac1.getBean("beanId");
ac2.getBean("beanId");

说明:这种方法适合于B/S模式,需要提供ServletContext,局限性比较大,至于以上两个方法区别是前者出错会抛出异常,而后者会返回null。

三. 继承自抽象类ApplicationObjectSupport

说明:抽象类ApplicationObjectSupport提供getApplicationContext()方法,可以方便的获取ApplicationContext。

Spring初始化时,会通过该抽象类的setApplicationContext(ApplicationContext context)方法将ApplicationContext 对象注入。

四. 继承自抽象类WebApplicationObjectSupport

说明:类似上面方法,调用getWebApplicationContext()获取WebApplicationContext

五:实现接口ApplicationContextAware

说明:实现该接口的setApplicationContext(ApplicationContext context)方法,并保存ApplicationContext 对象。Spring初始化时,会通过该方法将ApplicationContext对象注入。

  相比下来对于需要获取已经启动的bean。我们需要获取bean方法,这时我们可以通过实现接口ApplicationContextAware来获取。

  实际应用:

  一. SpringContextHolder类

package com.gren.supervise.commons;
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");
}
}
}

二. PropertyUtil

package com.gren.supervise.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
import com.gren.supervise.commons.SpringContextHolder;
import com.gren.supervise.dao.MapCnfDao;
import com.gren.supervise.pojo.MapCnf; /**
* 媒资系统配置文件参数获取工具
* */
public final class PropertyUtil {
private static Properties props;
private static MapCnfDao cnfDao; private PropertyUtil() {
} static {
cnfDao = (MapCnfDao) SpringContextHolder.getBean("cnfDao");
props = new Properties();
try {
props.load(PropertyUtil.class
.getResourceAsStream("/config.properties"));
} catch (IOException e) {
e.printStackTrace();
}
} public static Properties getSysProperties() {
Properties properties = new Properties();
List<MapCnf> cnfs = cnfDao.list();
for (int i = ; i < cnfs.size(); i++) {
properties.put(cnfs.get(i).getKey(), cnfs.get(i).getValue());
}
return properties;
} /**
* 获取指定的系统属性
*
* @param key
* 指定的属性名称
* @return 指定的系统属性值
*/
public static String getProperty(String key) {
ConditionFilter conditionFilter = new ConditionFilter("key", key,
ConditionFilter.EQ);
List<ConditionFilter> conditionFilters = new ArrayList<ConditionFilter>();
conditionFilters.add(conditionFilter);
List<MapCnf> cnfs = cnfDao.queryByCondition(conditionFilters);
if(null==cnfs){
return null;
}
return cnfs.get().getValue();
} /**
* 获取指定的系统属性
*
* @param key
* 指定的属性名称
* @param defaultVal
* 默认值
* @return 指定的系统属性值
*/
public static String getProperty(String key, String defaultVal) {
return getProperty(key);
} /*
* 修改属性
*/
public static void put(String key, String value) {
MapCnf entity = new MapCnf();
entity.setKey(key);
entity.setValue(value);
ConditionFilter conditionFilter = new ConditionFilter("key", key,
ConditionFilter.EQ);
List<ConditionFilter> conditionFilters = new ArrayList<ConditionFilter>();
conditionFilters.add(conditionFilter);
List<MapCnf> cnfs = cnfDao.queryByCondition(conditionFilters);
if(null!=cnfs&&cnfs.get().getId()>){
entity.setId(cnfs.get().getId());
cnfDao.saveOrupdate(entity);
}
} public static void toCnfMap() {
Enumeration enumeration = props.propertyNames();
while (enumeration.hasMoreElements()) {
String key = (String) enumeration.nextElement();
PropertyUtil.put(key, (String) props.get(key));
}
}
}

Spring获取bean的几种方式的更多相关文章

  1. Spring获取bean的一种方式

    随便一百度,网上一大把,并且还不止一种.所以这里就只记录目前用的一种好了. 实现ApplicationContextAware接口 即可: import org.springframework.bea ...

  2. spring 获取bean的几种方式

    1.读取xml文件的方式,这种在初学入门的时候比较适用 . ApplicationContext applicationContext = new ClassPathXmlApplicationCon ...

  3. spring创建bean的三种方式

    spring创建bean的三种方式: 1通过构造方法创建bean(最常用) 1.1 spring默认会通过无参构造方法来创建bean,如果xml文件是这样配置,则实体类中必须要有无参构造方法,无参构造 ...

  4. spring 注入bean的两种方式

    我们都知道,使用spring框架时,不用再使用new来实例化对象了,直接可以通过spring容器来注入即可. 而注入bean有两种方式: 一种是通过XML来配置的,分别有属性注入.构造函数注入和工厂方 ...

  5. Spring获取ApplicationContext方式,和读取配置文件获取bean的几种方式

    转自:http://chinazhaokeke.blog.163.com/blog/static/109409055201092811354236  Spring获取ApplicationContex ...

  6. Spring在代码中获取bean的几种方式

    方法一:在初始化时保存ApplicationContext对象 方法二:通过Spring提供的utils类获取ApplicationContext对象 方法三:继承自抽象类ApplicationObj ...

  7. Spring在代码中获取bean的几种方式(转:http://www.dexcoder.com/selfly/article/326)

    方法一:在初始化时保存ApplicationContext对象 方法二:通过Spring提供的utils类获取ApplicationContext对象 方法三:继承自抽象类ApplicationObj ...

  8. Spring在代码中获取bean的几种方式(转)

    获取spring中bean的方式总结: 方法一:在初始化时保存ApplicationContext对象 ApplicationContext ac = new FileSystemXmlApplica ...

  9. spring 装配bean的三种方式

    这段时间在学习Spring,依赖注入DI和面向切面编程AOP是Spring框架最核心的部分.这次主要是总结依赖注入的bean的装配方式. 什么是依赖注入呢?也可以称为控制反转,简单的来说,一般完成稍微 ...

随机推荐

  1. mvel

    https://en.wikipedia.org/wiki/MVEL import java.util.*; // the main quicksort algorithm def quicksort ...

  2. linux运维 vi vim q 的间接注释

    w q  --不发生写的写,无增删效果. 点q后,再次执行 vi /var/www/share/w.php 仍然会‘ Found a swap file by the name "/var/ ...

  3. SQL中的函数 •Aggregate 函数 •Scalar 函数

    合计函数  :Aggregate是针对一系列值的操作,返回一个单一的值 Scalar 函数是针对一个单一的值的操作,返回基于输入值的一个单一值 合计函数: AVG()返回某列的平均值:COUNT()返 ...

  4. 转!!Java设置session超时(失效)的时间

    Java设置session超时(失效)的时间   在一般系统登录后,都会设置一个当前session失效的时间,以确保在用户长时间不与服务器交互,自动退出登录,销毁session具体设置的方法有三种:1 ...

  5. Python 一键同步windows和linux数据(基于pscp.exe)

    outline 项目中需要把 windows server 上的数据同步到 linux server,方法很多,这里记录下自己采用的一种比较简单的方法. 准备工作 首先确保你 windows serv ...

  6. HDU3552(贪心)

    题目是将一系列点对(a,b)分成两个集合.使得A集合的最大a+B集合的最大数b得和最小. 思路:http://blog.csdn.net/dgq8211/article/details/7748078 ...

  7. beego——过滤器

    beego支持自定义过滤中间件,例如安全验证.强制跳转等. 过滤器函数如下所示: beego.InsertFilter(pattern string, position int, filter Fil ...

  8. go——数组(二)

    1.内部实现 在Go语言里,数组是一个长度固定的数据类型,用于存储一段具有相同的类型的元素的连续块. 数组存储的类型可以是内置类型,如整型或字符串,也可以是某种结构类型. 灰格子代表数组里面的元素,每 ...

  9. JavaScript 函数,math对象,Date对象 序列化 总结

    函数 函数定义 // 普通函数定义 function f1() { console.log("Hello world!"); } // 带参数的函数 function f2(a, ...

  10. 动态更改WebBrowser数据流内容

    动态更改WebBrowser数据流内容       有时,由于软件的特殊需要,我们希望DELPHI在WebBrowser或embeddedwb里动态更改返回的数据内容,而这需要返回网页的所有原始源码, ...