Spring中直接获取bean的工具类
来源:互联网 发布:淘宝的体验中心在哪里 编辑:程序博客网 时间:2024/05/19 00:16
转载出处:http://blog.csdn.net/wklken/archive/2011/04/23/6342977.aspx
Spring 中直接获取 bean 的工具类 此方法不需要将bean在配置文件中注入到使用类
1. 建立 listener ,启动时加载配置
public class ApplicationListener implements ServletContextListener { public void contextInitialized(ServletContextEvent event) { ServletContext context = event.getServletContext(); try { initContextUtil(context); } catch (Exception ex) { ex.printStackTrace(); } } public void contextDestroyed(ServletContextEvent sce) { } private void initContextUtil(ServletContext context) throws Exception{ ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context); ContextUtil.setContext(ctx); } }
2. 对应的工具类
public class ContextUtil { private static ApplicationContext context; public static ApplicationContext getContext() { return context; } public static Object getBean(String beanId) throws Exception { Object bean = context.getBean(beanId); if (bean == null) return null; return bean; } public static void setContext(ApplicationContext ctx) { context = ctx; } }
3. 在 web.xml 中配置对应的 listener
<listener> <listener-class> com.test.listener.ApplicationListener </listener-class> </listener>
4. 使用 根据在 application 中配置的 bean 的 id 获取对应的 dao 实例
XXDAO xxDao =(XXDAO)ContextUtil.getContext ().getBean( "xxDAO" );
若是非WEB工程使用spring 修改如下:【注意配置文件路径的修改】将context初始化方法修改如下,并在程序启动时调用
public static void initApplicationContext() { System.out.println("初始化context....开始"); ApplicationContext context = new ClassPathXmlApplicationContext( "classpath:config/spring-config.xml"); ContextUtil.setContext(context); System.out.println("初始化context....结束"); }
- Spring中直接获取bean的工具类
- Spring中直接获取bean的工具类
- Spring中直接获取bean的工具类
- 在jsp中直接获取spring中的bean实例
- DWR中直接获取一个JAVA类的返回值
- 浅谈Flex中直接获取某个组件的对象
- [笔记]shell中直接获取crash工具下的bt和log文件的方法
- 在多个EditText中直接获取某个焦点
- 快速从数据库中直接获取数据字典
- 从spring容器中直接取bean的方法
- EL表达式 获取list长度/不用循环,EL在List中直接获取第一项的内容/EL获取Map的键,Map的值
- 编程从广义表字符串表示中直接获取广义表有关信息
- 可以随时拿取spring容器中Bean的工具类
- 通过类似GetComponent从组件中直接获得接口的三种方式
- java中直接获得session对象
- java取spring的bean
- 让WebApp在浏览器中直接获得原生应用体验 - 基于Rexsee开发平台的UP移动浏览器发布测试
- spring获取bean工具类
- 网络bbs详解
- spring mvc代码详解 三
- Oracle cursor的用法.
- Javascript style guide
- listview android:cacheColorHint,android:listSelector属性作用
- Spring中直接获取bean的工具类
- 双向实时远程同步文件(inotify+rsync与nfs)
- web前端安全编码(模版篇)
- WP开发心得分享:敏捷开发提升团队开发效率
- 黑客诡计
- 在SQL Server中对视图进行增删改
- 解决main No MyBatis mapper was found in 的警告
- telnet命令模式
- Linux下用户和文件(或是目录)的关系