我们经常需要获取各种 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. Linux下ps命令详解 Linux下ps命令的详细使用方法

    http://www.jb51.net/LINUXjishu/56578.html Linux下的ps命令比较常用 Linux下ps命令详解Linux上进程有5种状态:1. 运行(正在运行或在运行队列 ...

  2. python-open文件处理

    python内置函数open()用于打开文件和创建文件对象 语法 open(name[,mode[,bufsize]]) name:文件名 mode:指定文件的打开模式 r:只读 w:写入 a:附加 ...

  3. plain framework 1 1.0.4 更新 稳定版发布

    PF由于各种因素迟迟不能更新,此次更新主要是更新了以往和上个版本出现的内存问题,该版本较为稳定,如果有用到的朋友请更新至此版本. PF 1.0.4 修复1.0.0.3更新后产生的内存问题,可能导致网络 ...

  4. [LeetCode] Find Median from Data Stream 找出数据流的中位数

    Median is the middle value in an ordered integer list. If the size of the list is even, there is no ...

  5. Suspend to RAM和Suspend to Idle分析,以及在HiKey上性能对比

    Linux内核suspend状态 Linux内核支持多种类型的睡眠状态,通过设置不同的模块进入低功耗模式来达到省电功能.目前存在四种模式:suspend to idle.power-on standb ...

  6. Zabbix2.4.7源码安装手册

    一.安装Apache Server 注:使用root安装后,变更拥有者为your-user 1 安装环境 系统: CentOS release 6.6 软件: httpd-2.2.31 2 安装步骤 ...

  7. uicode编码解码

    .版本 2.支持库 dp1 bydess = 字节集_还原 (到文本 (bytes)) ' HEX解码返回 (到文本 (解密数据 (bydess, “debugme?”, #RC4算法))) impo ...

  8. iOS开发中遇到的错误整理 - 集成第三方框架时,编译后XXX头文件找不到

    iOS编译报错-XXX头文件找不到 错误出现的情况: 自己在继承第三方的SDK的时候,明明导入了头文件,但是系统报错,提示头文件找不到 解决方法 既然系统找不到,给他个具体路径,继续找去! 路径就填写 ...

  9. .技术参数图用pillow自动处理

    python 2.7 pillow 安装python2.7.10(自带pip),修改豆瓣源,下载pillow

  10. pyMysql

    本篇对于Python操作MySQL主要使用两种方式: 原生模块 pymsql ORM框架 SQLAchemy pymsql pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb ...