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 block
e.printStackTrace();
}
return conn;
}