我有一个名为App.java的swing类,我有这个:
private EmployeeService employeeService;
public void setEmployeeService(EmployeeService employeeService) {
this.employeeService = employeeService;
}
在我的applicationContext.xml中,我有这个:
<bean id="employeeDao" class="com.myapp.dao.EmployeeDaoImpl">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="employeeService" class="com.myapp.service.EmployeeServiceImpl">
<property name="employeeDao" ref="employeeDao" />
</bean>
<bean id="app" class="com.myapp.swing.App">
<property name="employeeService" ref="employeeService" />
</bean>
当我运行App.java时,我收到employeeService为null的错误。为什么会这样?如果我直接从类中分配employeeService bean:
ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("/spring/applicationContext.xml");
EmployeeService employeeService = (EmployeeService) context.getBean("employeeService");
employeeService.validateEmployeeNo(1234);
context.close();
...
我能够成功运行它。当我从applicationContext.xml注入它时,不是在App.java中连接employeeService吗?
答案 0 :(得分:0)
除非您的App类是由Spring容器创建的,否则您将尝试访问任何服务的null。你是如何初始化你的App类的?
App myApp = new App();
或
App myApp = (App) context.getBean("app");