sti*_*vlo 2 java spring dependency-injection
在我的main()方法中,我使用Spring创建一个PersonCollection对象,然后我开始加载不同的Persons对象.
BeanFactory appContext = new ClassPathXmlApplicationContext("cp-beans.xml");
PersonCollection pc = appContext.getBean(PersonCollection.class);
Person aPerson = pc.loadById(1);
aPerson.doSomething();
aPerson.loadById(1067);
aPerson.doSomething();
Run Code Online (Sandbox Code Playgroud)
反过来,PersonCollection.loadById()可以从memcached或Amazon SimpleDB加载对象:
public Person loadById(int id) throws ConnectException, NoSuchElementException {
String memCacheKey = "Person-" + id;
Person aPerson = (Person) cache.get(memCacheKey);
if (aPerson != null) {
return aPerson; //cache hit
}
aPerson = loadByIdFromSdb(id); //cache miss, read it from SimpleDB
cache.set(memCacheKey, aPerson);
return aPerson;
}
Run Code Online (Sandbox Code Playgroud)
因此有两种方法可以创建Person,第一种是从memcached反序列化,第二种是调用new Person()并分配所有数据.
Person有两个@Autowired属性并被声明为@Service,并且包在上下文中:component-scan,但是不传递依赖项,因为bean是使用new创建的,或者是从缓存而不是使用Spring框架创建的.
我可以使用appContext.getBean()来创建Person对象,但是,它意味着传递applicationContext并在应用程序中使用getBean(),这感觉不对.
如何解决问题?
更新:我阅读了文档并尝试了Ryan Stewart的建议,并编写了一个小示例项目来尝试它.它很棒,谢谢!
https://github.com/stivlo/spring-di
最终,我已经重构了我原来的项目,我不再需要这个功能,但是在我的武器库里有一个很好的工具.
ApplicationContext.getBean()使用像瘟疫这样的(非基础设施)代码.| 归档时间: |
|
| 查看次数: |
1069 次 |
| 最近记录: |