spring获取bean工具类

xiaoxiao2021-02-28  128

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; } }
转载请注明原文地址: https://www.6miu.com/read-21365.html

最新回复(0)