[Java] ApplicationContext 辅助类
我们经常需要获取各种 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 辅助类的更多相关文章
- Java并发辅助类的使用
目录 1.概述 2.CountdownLatch 2-1.构造方法 2-2.重要方法 2-3.使用示例 3.CyclicBarrier 3-1.构造方法 3-2.使用示例 4.Semaphore 4- ...
- 第65节:Java后端的学习之Spring基础
Java后端的学习之Spring基础 如果要学习spring,那么什么是框架,spring又是什么呢?学习spring中的ioc和bean,以及aop,IOC,Bean,AOP,(配置,注解,api) ...
- 【Spring】浅析Spring框架的搭建
c目录结构: // contents structure [-] Spring是什么 搭建Spring框架 简单Demo 1,建立User类 2,建立Test类 3,建立ApplicationCont ...
- Spring学习笔记 1. 尚硅谷_佟刚_Spring_HelloWorld
1,准备工作 (1)安装spring插件 搜索https://spring.io/tools/sts/all就可以下载最新的版本 下载之后不用解压,使用Eclipse进行安装.在菜单栏最右面的Help ...
- Spring学习进阶(二)Spring IoC
在使用Spring所提供的各种丰富而神奇的功能之前,必须在Spring IoC容器中装配好Bean,并建立Bean与Bean之间的关联关系.控制反转(Inverser of Control ioc)是 ...
- spring学习起步
1.搭载环境 去spring官网下载这几个包,其中commons-logging-1.2.jar是一个日志包,是spring所依赖的包,可以到apache官网上下载 也可以访问http://downl ...
- Spring源码阅读-spring启动
web.xml web.xml中的spring容器配置 <listener> <listener-class>org.springframework.web.context.C ...
- 实战 PureMVC
最近看PureMVC,在IBM开发者社区发现此文,对PureMVC的讲解清晰简洁,看了可快速入门.另外,<腾讯桌球>游戏的开发者吴秦,也曾进一步剖析PureMVC,可结合看加深理解. 引言 ...
- spring的配置与使用
spring的配置与使用 一.Spring介绍 1. 什么是Spring Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由 RodJohnson 在其著 ...
随机推荐
- 编译protobuf的jar文件
1.准备工作 需要到github上下载相应的文件,地址https://github.com/google/protobuf/releases protobuf有很多不同语言的版本,因为我们需要的是ja ...
- mysql数据类型
一.数值类型 Mysql支持所有标准SQL中的数值类型,其中包括严格数据类型(INTEGER,SMALLINT,DECIMAL,NUMBERIC),以及近似数值数据类型(FLOAT,REAL,DOUB ...
- Spring MVC之@RequestMapping 详解
(转自:http://blog.csdn.net/walkerjong/article/details/7994326) 引言: 前段时间项目中用到了RESTful模式来开发程序,但是当用POST.P ...
- ubuntu kylin 14.04安装配置MongoDB v2.6.1(转)
1.获取最新版本 https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-2.6.1.tgz 2.解压并进入bin目录 tar zxvf mongo ...
- Java并发基础总结
并发是一种能并行运行多个程序或并行运行一个程序中多个部分的能力.如果程序中一个耗时的任务能以异步或并行的方式运行,那么整个程序的吞吐量和可 交互性将大大改善.现代的PC都有多个CPU或一个CPU中有多 ...
- java基础学习03(java基础程序设计)
java基础程序设计 一.完成的目标 1. 掌握java中的数据类型划分 2. 8种基本数据类型的使用及数据类型转换 3. 位运算.运算符.表达式 4. 判断.循环语句的使用 5. break和con ...
- python学习4
1.python中的函数的参数,这个参数的设置比起C比较特殊的地方就是参数可以预保留的.这个意思就是可以保留下来不填写,然后需要的时候再传入. 这个调用之后结果如下,另外可以看出python比起C来一 ...
- Web Service
Web Service全称XML Web Service WebService是一种可以接收从Internet或者Intranet上的其它系统中传递过来的请求,轻量级的独立的通讯技术.是:通过SOAP ...
- .Net环境下的缓存技术介绍 (转)
.Net环境下的缓存技术介绍 (转) 摘要:介绍缓存的基本概念和常用的缓存技术,给出了各种技术的实现机制的简单介绍和适用范围说明,以及设计缓存方案应该考虑的问题(共17页) 1 概念 ...
- [LeetCode] Super Pow 超级次方
Your task is to calculate ab mod 1337 where a is a positive integer and b is an extremely large posi ...