我们经常需要获取各种 bean , 需要用到 context。

下面的类可以方便的使用 context , 获取 bean 等。

import java.io.File;
import java.util.ArrayList;
import java.util.List; import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext; /**
* 单例上下文对象,配合 spring 使用, 用于获取 Bean
* @author YangYxd
* @see 在配置中(applicationContext.xml) 加入
* <bean id="SpringApplicationContext" class="包名.ContextHelper"></bean>
*/
public class ContextHelper implements ApplicationContextAware {
private static String XMLName = "applicationContext.xml";
private static ApplicationContext applicationContext = null; private static class ApplicationContextHolder { // 初始化 Context, 尝试搜索常用的存放 ApplicationContext.xml 的位置
public static ApplicationContext Init() {
ApplicationContext context = null;
try {
context = new ClassPathXmlApplicationContext(XMLName);
} catch (Exception e) {}
// 在当前项目中搜索配置文件
if (context == null) {
try {
String fileName = findFile(System.getProperty("user.dir"), XMLName);
if (fileName != null)
context = new FileSystemXmlApplicationContext(fileName);
} catch (Exception e) {}
}
return context;
} } // 私有化的构造方法,保证外部的类不能通过构造器来实例化。
private ContextHelper() {} /** 设定 XML 名称 */
synchronized public static void setXmlName(String name) {
XMLName = name;
} // 获取单例对象实例
synchronized public static ApplicationContext getInstance() {
if (applicationContext != null)
return applicationContext;
applicationContext = ApplicationContextHolder.Init();
return applicationContext;
} /**
* 如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true
* @param name
* @return boolean
*/
public static boolean containsBean(String name) {
return getInstance().containsBean(name);
} /**
* @param name
* @return Class 注册对象的类型
*/
public static Class<?> getType(String name) {
try {
return getInstance().getType(name);
} catch (Exception e) {
return null;
}
} /**
* 如果给定的bean名字在bean定义中有别名,则返回这些别名
* @param name
* @return
*/
public static String[] getAliases(String name) {
try {
return getInstance().getAliases(name);
} catch (Exception e) {
return null;
}
} /**
* 判断以给定名字注册的bean定义是一个singleton还是一个prototype。
* 如果与给定名字相应的bean定义没有被找到,也会返回 false
* @param name
* @return boolean
*/
public static boolean isSingleton(String name) {
try {
return getInstance().isSingleton(name);
} catch (Exception e) {
return false;
}
} @SuppressWarnings("static-access")
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
System.out.println("ApplicationContextHelper setApplicationContext OK.");
} /**
* 查找文件
* @param baseDirName 查找的文件夹路径
* @param targetFileName 需要查找的文件名
*/
public static String findFile(String baseDirName, String targetFileName) {
List<File> files = new ArrayList<File>();
findFiles(baseDirName, targetFileName, files, true);
if (files.isEmpty())
return null;
return files.get(0).getPath();
} /**
* 递归查找文件
* @param baseDirName 查找的文件夹路径
* @param targetFileName 需要查找的文件名
* @param fileList 查找到的文件集合
* @param onlyFirst 是否是查找第一个
*/
public static void findFiles(String baseDirName, String targetFileName, List<File> fileList, Boolean onlyFirst) { File baseDir = new File(baseDirName); // 创建一个File对象
if (!baseDir.exists() || !baseDir.isDirectory()) { // 判断目录是否存在
System.out.println("文件查找失败:" + baseDirName + "不是一个目录!");
}
String tempName = null;
//判断目录是否存在
File tempFile;
File[] files = baseDir.listFiles();
for (int i = 0; i < files.length; i++) {
tempFile = files[i];
if(tempFile.isDirectory()){
findFiles(tempFile.getAbsolutePath(), targetFileName, fileList, onlyFirst);
}else if(tempFile.isFile()){
tempName = tempFile.getName();
if (tempName != null && tempName.equalsIgnoreCase(targetFileName)) {
// 匹配成功,将文件名添加到结果集
fileList.add(tempFile.getAbsoluteFile());
if (onlyFirst)
return;
}
}
}
} /**
* 获取 Bean
* @param beanName
* @return
*/
@SuppressWarnings("unchecked")
public static <T extends Object> T getBean(String beanName) {
try {
return (T)getInstance().getBean(beanName);
} catch (BeansException e) {
e.printStackTrace();
return null;
}
} /**
* 获取 Bean
* @param beanName
* @param clazz
* @return
*/
public static <T extends Object> T getBean(String beanName , Class<T>clazz) {
return getInstance().getBean(beanName , clazz);
} /**
* @param clazz 通过类模板获取该类
* @return 该类的实例,默认单例
*/
public static <T extends Object> T getBean(Class<T> clazz){
try {
return getInstance().getBean(clazz);
} catch (BeansException e) {
e.printStackTrace();
return null;
}
} }

在单元测试中使用:

package com.yxd.example.bean;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.springframework.test.context.ContextConfiguration; @RunWith(BlockJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:applicationContext.xml"})
public class SpringTest { @Test
public void enumBeans() {
//获取spring装配的bean个数
int beanCount = ContextHelper.getInstance().getBeanDefinitionNames().length;
//逐个打印出spring自动装配的bean。根据我的测试,类名第一个字母小写即bean的名字
for(int i=0; i<beanCount; i++){
System.out.println(ContextHelper.getInstance().getBeanDefinitionNames()[i]);
}
}
}

在这个测试类中,加入ContextConfiguration注解后,会自动加载配置文件。

[Java] ApplicationContext 辅助类的更多相关文章

  1. Java并发辅助类的使用

    目录 1.概述 2.CountdownLatch 2-1.构造方法 2-2.重要方法 2-3.使用示例 3.CyclicBarrier 3-1.构造方法 3-2.使用示例 4.Semaphore 4- ...

  2. 第65节:Java后端的学习之Spring基础

    Java后端的学习之Spring基础 如果要学习spring,那么什么是框架,spring又是什么呢?学习spring中的ioc和bean,以及aop,IOC,Bean,AOP,(配置,注解,api) ...

  3. 【Spring】浅析Spring框架的搭建

    c目录结构: // contents structure [-] Spring是什么 搭建Spring框架 简单Demo 1,建立User类 2,建立Test类 3,建立ApplicationCont ...

  4. Spring学习笔记 1. 尚硅谷_佟刚_Spring_HelloWorld

    1,准备工作 (1)安装spring插件 搜索https://spring.io/tools/sts/all就可以下载最新的版本 下载之后不用解压,使用Eclipse进行安装.在菜单栏最右面的Help ...

  5. Spring学习进阶(二)Spring IoC

    在使用Spring所提供的各种丰富而神奇的功能之前,必须在Spring IoC容器中装配好Bean,并建立Bean与Bean之间的关联关系.控制反转(Inverser of Control ioc)是 ...

  6. spring学习起步

    1.搭载环境 去spring官网下载这几个包,其中commons-logging-1.2.jar是一个日志包,是spring所依赖的包,可以到apache官网上下载 也可以访问http://downl ...

  7. Spring源码阅读-spring启动

    web.xml web.xml中的spring容器配置 <listener> <listener-class>org.springframework.web.context.C ...

  8. 实战 PureMVC

    最近看PureMVC,在IBM开发者社区发现此文,对PureMVC的讲解清晰简洁,看了可快速入门.另外,<腾讯桌球>游戏的开发者吴秦,也曾进一步剖析PureMVC,可结合看加深理解. 引言 ...

  9. spring的配置与使用

    spring的配置与使用 一.Spring介绍 1. 什么是Spring Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由 RodJohnson 在其著 ...

随机推荐

  1. 强大的flash头像上传插件(支持旋转、拖拽、剪裁、生成缩略图等)

    今天介绍的这款flash上传头像功能非常强大,支持php,asp,jsp,asp.net 调用 头像剪裁,预览组件插件. 本组件需要安装Flash Player后才可使用,请从http://dl.pc ...

  2. Windows Server 2012 虚拟化实战:存储(二)

    五.搭建Window Server 2012虚拟化的存储网络 前文我们讨论了Window Server 2012支持的各种与存储相关的技术,接下来我们通过实践对其中的一些技术进行检验.实际上Windo ...

  3. 64位下pwntools中dynELF函数的使用

    这几天有同学问我在64位下怎么用这个函数,于是针对同一道题写了个利用dynELF的方法 编译好的程序 http://pan.baidu.com/s/1jImF95O 源码在后面 from pwn im ...

  4. sql一个表中的数据插入到另外一个表中

    声名:a,b ,都是表 复制代码代码如下: --b表存在(两表结构一样)  insert into b select * from a  若两表只是有部分(字段)相同,则 复制代码代码如下: inse ...

  5. Statement对象的executeUpdate返回信息

    int num = sta.executeUpdate(String sql);返回的是我们平时操作数据库客户端时控制台显示的影响行数

  6. EEG preprocessing - A Trick Before Doing ICA

    EEGLab maillist My ICs don't have high power in low frequency is b/c I do a small trick here. before ...

  7. [LeetCode] Read N Characters Given Read4 II - Call multiple times 用Read4来读取N个字符之二 - 多次调用

    The API: int read4(char *buf) reads 4 characters at a time from a file. The return value is the actu ...

  8. 如何在一台新电脑上配置JAVA开发环境

    对于JAVA新手来说,刚开始要学JAVA,而自己的电脑上毫无与JAVA开发有关的环境,应该如何进行配置呢? (安卓新手也需要JAVA开发环境) 第一步,下载.安装java JRE JRE (Java ...

  9. 《虚拟伙伴》AR增强现实应用开发总结

    一.概述 1.1选题背景 随着时代的发展,人们的生活节奏越来越快,生活质量也越来越高,但却在繁忙之中忽略或者忘记了关心自己成长时代最重要或者最正确的事情和道理.虽然现在有很多社交平台,如微博,微信,f ...

  10. mac 多php版本安装

    mac上自带又apache和php. 自带的php缺少一些扩展(freeType),安装起来因为mac本身有一些sudo su都不可触及的权限,所以决定不动系统本身php,再装一个新的php不同版本. ...