I have a simple code to understand Spring DI functionality.
Here is my code in tester.java
:
package com.email;
@Component
public class Tester {
@Autowired
private static EmailService emailService;
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
System.out.println("emailService: " + emailService); // is null
}
}
interface EmailService {
String sayHello();
}
@Component
class EmailServiceImpl implements EmailService {
public String sayHello() {
return "Hello";
}
}
And here is in spring-config.xml
:
<bean id="emailService" class="com.email.EmailServiceImpl"/>
<context:annotation-config/>
<context:component-scan base-package="com.email"/>
I declared the emailService
bean which refers to EmailServiceImpl
class , why i get null
in emailService
?
The annotation doesn't work because the field is static
. Change it to
@Autowired
private EmailService emailService;
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments