我有了弹簧注入道(下文简化的)一个单:依赖注入到你的单身
public class MyService<T> implements Service<T> {
private final Map<String, T> objects;
private static MyService instance;
MyDao myDao;
public void set MyDao(MyDao myDao) {
this. myDao = myDao;
}
private MyService() {
this.objects = Collections.synchronizedMap(new HashMap<String, T>());
// start a background thread that runs for ever
}
public static synchronized MyService getInstance() {
if(instance == null) {
instance = new MyService();
}
return instance;
}
public void doSomething() {
myDao.persist(objects);
}
}
我的Spring配置可能会是这样的:
<bean id="service" class="MyService" factory-method="getInstance"/>
但是,这将实例启动期间的MyService。
有没有一种编程方式来执行MyDao到MyService的依赖注入,但没有春天管理MyService?
基本上,我希望能够从我的代码做到这一点:
MyService.getInstance().doSomething();
而有弹性注入MyDao我。
你必须在需要的地方使用ApplicationContext获取bean? – Langali 2010-05-18 20:22:31
我会*通常*在初始化时获得我的一个顶级bean,然后根据需要从顶级bean中引用更多的bean。但你可以做你的建议。 – 2010-05-18 20:29:31