【Spring】非SPRING管理的对象要引用SPRING容器管理的对象?对象之间如何引用?
来源:互联网 发布:测量员软件怎么用 编辑:程序博客网 时间:2024/05/17 06:48
最近项目中就有如题的一个需求,有些对象,不希望将其交给spring容器去管理,想通过自己new的方式去实例化,以便自己更好的去维护这个对象。
这里非SPRING管理的对象,即自己实例化的对象,用A来代替,SPRING管理的对象用B来代替
在网上找了很久,最终搞定了,这里先说一个弯路:
ApplicationContext context = new ClassPathXmlApplicationContext( "classpath*:spring/spring-*.xml"); return (CommonService) context.getBean("commonService");如上图所示,A类想引用B类,于是在A类中写了如上的方法来获取B类,启动项目后发现,一旦引用B类时,spring的所有对象就会再次实例化,通过JVM监控发现,对象快要撑爆了,果断放弃,说明如上方法和WEB容器启动加载不是共享的,是独立的,WEB容器启动加载了spring的所有对象,上面方法在被引用时又加载了,这就重复了,引用多少次,就重复多少次,巨坑啊!!!!
找寻spring容器的方法,从spring容器里去拿一个刚刚被spring容器实例化的对象,这样就不会重复加载了,拿的是实例化后的共享的一个对象
定义一个类实现自BeanFactoryAware接口
public class ServiceLocator implements BeanFactoryAware { private static BeanFactory beanFactory = null; private static ServiceLocator serviceLocator = null; @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { ServiceLocator.beanFactory = beanFactory; } public BeanFactory getBeanFactory() { return beanFactory; } public static ServiceLocator getInstance() { if (serviceLocator == null) { serviceLocator = (ServiceLocator) beanFactory.getBean("serviceLocator"); } return serviceLocator; } public static Object getService(String serviceName) { return beanFactory.getBean(serviceName); }}这样在A类中,如果要引用B类的话,通过上述类的静态方法getService即可,将bean的名字传入
private CommonService getCommonService() { /*@SuppressWarnings("resource") ApplicationContext context = new ClassPathXmlApplicationContext( "classpath*:spring/spring-*.xml"); return (CommonService) context.getBean("commonService");*/ return (CommonService) ServiceLocator.getService("commonService"); }如上,亲测成功
这样,非SPRING管理对象和SPRING管理对象就完美的结合到了一起
0 0
- 【Spring】非SPRING管理的对象要引用SPRING容器管理的对象?对象之间如何引用?
- Spring容器管理对象
- spring容器管理对象
- web 工程中 非spring 管理的对象 调用 spring 容器中对象
- Spring 使new方法创建的对象可以引用spring管理的bean.
- Spring 实现引用对象中值的注入
- spring中实例化父类中引用的对象
- 第四章 Spring.Net 如何管理您的类___让对象了解自己的容器
- Spring-IoC对象管理
- Spring 管理对象
- 普通类中引用spring 容器管理的bean
- 关于Spring管理的类如何创建对象。
- Hibernate和Spring的对象关系管理-
- 获取Spring管理的对象实例
- Spring整合jsf的管理bean对象
- 过滤器中注入spring管理的对象
- Spring的bean管理-注解创建对象
- spring容器对象的生命周期
- android 蓝牙SPP协议通信
- Linux 系列(六)——Nginx实现多虚拟主机配置
- Middle-题目23:121. Best Time to Buy and Sell Stock
- Authority-check基础知识
- 关于spring事务中readonly
- 【Spring】非SPRING管理的对象要引用SPRING容器管理的对象?对象之间如何引用?
- 数值挖坑笔记
- JavaScript学习--Item26 异步的脚本加载
- 分数中的运算符重载(2)
- iOS库的介绍以及如何使用CocoaPods管理库(2016最新版本)
- A+B Problem (0)
- web前端工程师需要掌握哪些知识
- minidlna配置
- maven创建项目时出现错误:Failed to execute goal org.apache.maven.plugins:maven-archetype-plugin