您的位置:首页 > 编程语言 > Java开发

Spring给普通对象注入依赖

2017-04-17 00:00 465 查看
摘要: 在普通的对象中需要Spring依赖注入但此类本身又不是Spring的Component

开发中碰到了一个情况自己定义了一个普通的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