0

I have encountered a scenario in my application where I am calling a library class method which uses autowiring with @Qualifier annotation. In my case, the behavior is exact same but the autowired bean should be different. This autowired bean simply calls a REST service.

I have tried to show the scenario with few simple classes:

public interface IMessage {
    public String getMessage();
}

public class HelloMessage implements IMessage {
    public String getMessage() {
        return "Hello";
    }
}

public class HiMessage implements IMessage  {
    public String getMessage() {
        return "Hi";
    }
}

public class PrintMessage { 
    @Qualifier("helloMessage")
    @Autowired
    private IMessage message;

    public void service() {
        System.out.println(message.getMessage());
    }
}

Suppose all these classes belong to library. The only thing I am trying to achieve is HiMessage bean to be autowired in PrintMessage class. Overriding this class would be simple solution but since the service() method behavior is exact same so I don't want to override it just for using different autowired bean.

M. Deinum
  • 115,695
  • 22
  • 220
  • 224
  • Whatever bean you create name it `helloMessage`. – M. Deinum Sep 23 '18 at 16:44
  • answer would be here: https://stackoverflow.com/questions/40830548/spring-autowired-and-qualifier – tharanga-dinesh Sep 23 '18 at 16:59
  • @M.Deinum How can you declare two beans with same id? Alias option is there but that would also require redefining the behavior in a different bean. – Sumit Srivastava Sep 23 '18 at 17:03
  • Why would you need to change the behavior? When creating a bean with the same name it will override the other one, hence the `HiMessage` bean is availabel and will be injected. – M. Deinum Sep 23 '18 at 17:24

2 Answers2

0

In your @Configuration class, create a @Bean("helloMessage")-annotated method which just returns the desired bean:

@Bean("helloMessage)"
public IMessage republishHiMessage() {
    return new HiMessage();
}

or by using parameter injection, if your desired object is already known as hiMessage:

@Bean("helloMessage)"
public IMessage republishHiMessage(@Qualifier("hiMessage") IMessage hiMessage) {
    return hiMessage;
}
Hero Wanders
  • 3,237
  • 1
  • 10
  • 14
0

For Example in following case it is necessary provide a qualifer.

@Component
@Qualifier("helloMessage")
public class HelloMessage implements IMessage {
    public String getMessage() {
        return "Hello";
    }
}

Hope this will be help for you. cheers!

tharanga-dinesh
  • 537
  • 6
  • 26