您的位置:首页 > 编程语言 > Java开发

spring获取bean工具类

2016-01-20 13:33 441 查看
import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;

import javax.servlet.ServletContext;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

/**
* 应用的共用方法
*
*/
public class ApplicationUtil {
public static ServletContext WEB_CONTEXT=null;
private static Properties config=null;
private static ApplicationContext context=null;
static{
load();
}
private static void load(){
try {
InputStream is=ApplicationUtil.class.getResourceAsStream("/config4j.properties");
config=new Properties();
config.load(is);
config.clone();
context=new FileSystemXmlApplicationContext("classpath:applicationContext.xml");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}
/**
* 获得config4中的配置属性的值
* @param propertyName 属性名
* @return 属性值
*/
public static String getProperty(String propertyName) {
String result="";
if (config!=null) {
result=config.getProperty(propertyName);
}
return result;
}
/**
* 获得配置的Bean的方法
* @param beanName
* @return
*/
public static Object getBean(String beanName) {
return context.getBean(beanName);
}
/**
* 解析XML获得根节点
* @param xml
* @return 根节点的Element对象
* @throws DocumentException
*/
public static Element getRootElementFromXML(String xml) throws DocumentException{
SAXReader reader=new SAXReader();
Document document=null;
try {
document = reader.read(new ByteArrayInputStream(xml.getBytes("utf-8")));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return document.getRootElement();
}

public static synchronized String getOnlyNumber() {
Calendar ca=Calendar.getInstance();
String result=""+ca.get(Calendar.HOUR)+ca.get(Calendar.MINUTE)+ca.get(Calendar.SECOND)+ca.get(Calendar.MILLISECOND);
return result;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: