Spring给普通对象注入依赖
2017-04-17 00:00
465 查看
摘要: 在普通的对象中需要Spring依赖注入但此类本身又不是Spring的Component
开发中碰到了一个情况自己定义了一个普通的Java类,此类需要自己来实例化但又不是Spring的Component,这个时候就需要Spring来把这个引用给注入进去,可以使用以下办法
开发中碰到了一个情况自己定义了一个普通的Java类,此类需要自己来实例化但又不是Spring的Component,这个时候就需要Spring来把这个引用给注入进去,可以使用以下办法
public class MyClass{ @Resource private MyComponent component; //do some things... }
MyClass newInstance = new MyClass(); //使用Spring依赖注入 AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor(); //指定自动注入的注解 Set<Class<? extends Annotation>> autowiredAnnotationTypes = new HashSet<>(); autowiredAnnotationTypes.add(Resource.class); autowiredAnnotationTypes.add(Autowired.class); autowiredAnnotationTypes.add(Value.class); bpp.setAutowiredAnnotationTypes(autowiredAnnotationTypes); //设置BeanFactory bpp.setBeanFactory(context.getAutowireCapableBeanFactory()); //给类注入对象 bpp.processInjection(newInstance);
相关文章推荐
- spring 依赖对象的注入方式(3种) 和 公共属性的设置abstract="true" parent
- 使用dom4j:读取spring配置文件,实例化bean对象并注入依赖对象
- spring 在普通类中调用注入的对象
- Spring之对象依赖关系(依赖注入Dependency Injection)
- 关于spring依赖注入到普通类中为null的情况解决理解方案
- (5) 编码剖析Spring装配基本属性的原理【附加:注入依赖对象的两种方式】
- Spring中利用AOP对领域对象(非依赖注入的对象,如new操作符、反射的方式生存的对象)下面是spring配置文件的一部分 <context:load-time-weaver /> <be
- Spring注入依赖对象
- 用spring的注解建立bean与bean之间的关系组件装配及自动注入依赖对象
- Spring注入依赖对象
- 模拟spring注入依赖对象
- spring学习笔记3--依赖注入对象
- spring 依赖注入到直接new 对象
- spring容器DI依赖注入对象<三>
- Spring.NET教程(六)——依赖对象的注入(基础篇)
- 使用dom4j:读取spring配置文件,实例化bean对象并注入依赖对象
- spring学习笔记3——注入依赖对象
- Spring获取Bean对象以及依赖注入的实现原理
- Spring学习07--Bean对象的初始化(IOC的依赖注入)原理
- Spring整理系列(02)——spring依赖注入,组装对象之间的依赖关系