简体   繁体   中英

service variable is null when accessing from main class

I have a swing class called App.java, in there I have this:

private EmployeeService employeeService;

public void setEmployeeService(EmployeeService employeeService) {
    this.employeeService = employeeService;
}

and in my applicationContext.xml, I have this:

<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>

When I run App.java, I am receiving the error that employeeService is null. Why is that so? If I assign the employeeService bean directly from the class:

ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("/spring/applicationContext.xml");
EmployeeService employeeService = (EmployeeService) context.getBean("employeeService");
employeeService.validateEmployeeNo(1234);
context.close();

...

I am able to run it successfully. Isn't spring wiring employeeService in App.java when I inject it from applicationContext.xml?

Unless your App class is being created by the Spring container you are going to get null on any service you try to access. How are you initializing your App class?

App myApp = new App();

or

App myApp = (App) context.getBean("app");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM