Sajad
Sajad

Reputation: 2363

Spring autowired is null

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 ?

Upvotes: 1

Views: 763

Answers (2)

aweigold
aweigold

Reputation: 6889

The problem is that the field you are trying to set by autowiring is declared as static. It really doesn't make sense to use dependency injection on a static field from a design perspective, but if you must, you can use a setter method.

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

Upvotes: 1

Roman C
Roman C

Reputation: 1

The annotation doesn't work because the field is static. Change it to

@Autowired
private EmailService emailService;

Upvotes: 4

Related Questions