Spring自动装配为空

时间:2015-07-17 12:30:59

标签: java spring dependency-injection autowired

我有一个简单的代码来理解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

2 个答案:

答案 0 :(得分:4)

注释不起作用,因为该字段为static。将其更改为

@Autowired
private EmailService emailService;

答案 1 :(得分:1)

问题是您尝试通过自动装配设置的字段被声明为静态。从设计角度对静态字段使用依赖注入确实没有意义,但如果必须,可以使用setter方法。

@Autowired
void setEmailService (EmailService emailService) {
  Tester.emailService = emailService;
}