Yotam Eliraz
Yotam Eliraz

Reputation: 97

Spring injection via Qualifier inject null instead of object

this simple code should implements a naive factory via Java Spring. the result however is null pointer, because the Human object isn't being injected an object (so it stays null).

what am I doing wrong?

Thanks

Config

@Configuration
 public class Config {

    @Bean(name = "Male")
    public Human getMale(){
        return new Male();
    }
    @Bean(name = "Female")
    public Human getFemale(){
        return new Female();
    }
}

Human

@Service
public interface Human {
    String getName();
    void setName(String nm);
}

Male and female implementations

@Service
public class Female implements Human{

    private  String name;

    public Female() {
        this.name = "Alice";
    }
    public String getName() {
        return name;
    }
    public void setName(String nm) {
        this.name=nm;
    }

}

@Service
public class Male implements Human{

    private  String name;

    public Male() {
        this.name = "Bob";
    }
    public String getName() {
        return name;
    }
    public void setName(String nm) {
        this.name=nm;
    }

}

Human Factory this is the class of the naive implementation of factory design pattern with spring.

@Service
public class HumanFactory {

    @Qualifier("Male")
    Human Male;

    @Qualifier("Female")
    Human female;

    public Human getMale() {
        return Male;
    }

    public Human getFemale() {
        return female;
    }

Main

@SpringBootApplication
public class AotSpringMain {

    public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(AotSpringMain.class, args);
        HumanFactory humanFactory = (HumanFactory)ctx.getBean("humanFactory");
        System.out.println(humanFactory.getMale().getName());

    }
}

Upvotes: 1

Views: 2012

Answers (1)

davidxxx
davidxxx

Reputation: 131324

@Qualifier doesn't enable the autowiring for the fields.
It is specified as :

This annotation may be used on a field or parameter as a qualifier for candidate beans when autowiring

So these :

@Qualifier("Male")
Human Male;

@Qualifier("Female")
Human female;

should be :

@Autowired
@Qualifier("Male")
Human Male;

@Autowired
@Qualifier("Female")
Human female;

Upvotes: 2

Related Questions