我有一个简单的代码来了解Spring DI功能。
这是我在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";
}
}
这是在
spring-config.xml
中:<bean id="emailService" class="com.email.EmailServiceImpl"/>
<context:annotation-config/>
<context:component-scan base-package="com.email"/>
我声明了引用
emailService
类的EmailServiceImpl
bean,为什么在null
中得到emailService
? 最佳答案
注释不起作用,因为该字段为static
。更改为
@Autowired
private EmailService emailService;
关于java - Spring 自动接线为空,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31475916/