spring 依赖注入到直接new 对象
2014-04-21 01:04
513 查看
当为遗留系统加入spring时,经典问题就是遗留系统需要引用spring管理的bean。幸好spring有机制可以处理这些。
建一个类实现ApplicationContextAware接口,有一个引用ApplicationContext的静态成员,然后,遗留系统需要引用spring管理的bean的地方,使用这个类。
1.比如:我这里建一个SpringContext类
2.然后在spring配置文件里加
<bean id="springContext" class="net.blogjava.chenlb.SpringContext"></bean>
3.其它类中引用
MyBean myBean = (MyBean) SpringContext.getContext().getBean("myBean");
4.如果老是写SpringContext.getContext().getBean("...");麻烦,可以建一个工厂类来返回你要的bean
建一个类实现ApplicationContextAware接口,有一个引用ApplicationContext的静态成员,然后,遗留系统需要引用spring管理的bean的地方,使用这个类。
1.比如:我这里建一个SpringContext类
package net.blogjava.chenlb; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; /** * 此类可以取得Spring的上下文. * Spring 使new方法创建的对象可以引用spring管理的bean. * 2007-10-18 上午11:12:33 * @author chenlb */ public class SpringContext implements ApplicationContextAware { protected static ApplicationContext context; public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { context = applicationContext; } public static ApplicationContext getContext() { return context; } }
2.然后在spring配置文件里加
<bean id="springContext" class="net.blogjava.chenlb.SpringContext"></bean>
3.其它类中引用
MyBean myBean = (MyBean) SpringContext.getContext().getBean("myBean");
4.如果老是写SpringContext.getContext().getBean("...");麻烦,可以建一个工厂类来返回你要的bean
package net.blogjava.chenlb; public class MyServerFactory { public static MyBean1 getMyBean1() { return (MyBean1) SpringContext.getContext().getBean("myBean1"); } }
相关文章推荐
- 直接new 对象 Spring 不会注入的解决方法
- 直接new 对象 Spring 不会注入的解决方法
- 在Servlet中可访问Spring bean对象,但是不能直接以注入的方式引用
- spring基于xml文件注入依赖对象
- spring注入的对象和new的对象到底有啥区别
- Spring之对象依赖关系(依赖注入Dependency Injection)
- Spring给普通对象注入依赖
- Spring整理系列(02)——spring依赖注入,组装对象之间的依赖关系
- Spring之对象依赖关系(依赖注入Dependency Injection)
- new出来的service对象和你在spring中注入的service对象不是同一个对象
- spring容器DI依赖注入对象<三>
- (4) 编码剖析Spring装配基本属性的原理【附加:注入依赖对象的两种方式】
- spring.net学习笔记1--依赖对象注入
- Spring注入依赖对象
- Spring学习07--Bean对象的初始化(IOC的依赖注入)原理
- 用spring做领域对象的依赖注入
- SpringIOC容器创建对象及依赖注入的几种方式
- Spring学习笔记——关于Spring注解扫描不能注入new对象问题
- 用spring的注解建立bean与bean之间的关系组件装配及自动注入依赖对象
- spring学习笔记3--依赖注入对象