Java类获取Spring的applicationContext.xml文件中的bean

来源:互联网 发布:淘宝买玩具枪犯法吗 编辑:程序博客网 时间:2024/05/22 02:15
public class UtilGetBean { public static Object getBean(String beanName) { ServletContext sc=ServletActionContext.getServletContext(); WebApplicationContext wc=WebApplicationContextUtils.getWebApplicationContext(sc); Object obj= wc.getBean(beanName); return obj; }}

以上工具类,只需传入bean的名称即可获取。

示例:(获取connection连接)

public static Connection getConnection(){Connection conn = null;try {ComboPooledDataSource dataSource = (ComboPooledDataSource)UtilGetBean.getBean("dataSource");conn = dataSource.getConnection();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}return conn;}



 

原创粉丝点击