我意识到这应该是非常基本的,但是在 Helloworld 之后我还没有找到第二步示例
所以我所拥有的是:
spring 配置 xml 称为 spring-beans.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:annotation-config />
<context:component-scan base-package="org" />
</beans>
一个弹簧上下文初始化的类:
public static void main(String[] args) {
// initialize Spring
ApplicationContext context = new ClassPathXmlApplicationContext("META-INF/spring-beans.xml");
App app = (App) context.getBean("app");
app.run();
}
AppImpl 类的相关细节:
@Component("app")
public final class AppImpl implements App{
// focus of question: This autowiring works
@Autowired
private DAO1 dao1;
public void run() {
//focus of question: This works as daoclass is instantiated properly
obj1s = dao1.myFind();
badJobs = runJobs(obj1s);
}
private List<Obj1> runJobs(final List<Obj1> obj1s) {
List<Obj1> jobsGoneBad = new ArrayList<Obj1>();
for (Obj1 next : obj1s) {
// focus of question: usage of new keyword, thus not spring container managed?
Job job = new JobImpl(next);
job.run();
}
return jobsGoneBad;
}
}
JobImpl的相关细节:
public class JobImpl implements Job {
private Obj1 obj1;
// focus of question: can't autowire
@Autowired
private DAO2 dao2;
@Override
public void run() {
//focus of question: opDAO == null - not initialized by @Autowired
Obj2 obj2 = dao2.myFind();
}
}
DAO1的相关细节:
@Repository("DAO1") //Focus of question: DAO1 is a repository stereotype
public class DAO1 {
myfind() { ...}
}
DAO2的相关细节:
@Repository("DAO2") //Focus of question: DAO2 is a repository stereotype
public class DAO2 {
myfind() { ...}
}
对,所以我通过 springcontext 调用初始化应用程序,然后通过使用 @Autowired 成功实例化 DAO1 实例。
然后我创建了一个 Job 的非托管实例,并希望通过使用 @Autowired 在该类中注入“singeltonish”依赖项
两个 Dao 类都是 spring 刻板印象,scanner 发现它们很好。
所以我的问题基本上是,我应该如何实例化作业实例以便我可以在其中使用 @Autowired 概念?
如果我需要一个全局可访问的应用程序上下文,我该如何最好地引入它?