Robert Kang
Robert Kang

Reputation: 568

Bean casting error from nested injections

I am working with Spring Integration with my project right now, specifically with MessageChannel/PublishSubscribeChannel. What I am trying to achieve is to create a broker module, so that other part of the system can call this module to send message to a specific MessageChannel.

Here is what I am doing now in the broker module:

@Configuration
public class BrokerConfiguration {
  @Bean
  public MessageChannel brokerChannel1() {
    return new PublishSubscribeChannel();
  }
}

and:

@Component
public class BrokerA {
  @Autowired
  @Qualifier("brokerChannel1")
  public MessageChannel messageChannel;

  public void sendAMessage() {
    messageChannel.send(MessageBuilder.withPayload("This is a message!").build());
  }
}

I have played around this setup by creating a SpringBootApplication within the broker module and it seems to work perfectly fine. However, when I try to use it in a different module of my system like this:

@Autowired
private BrokerA brokerA;

public void doSomethingHere() {
  brokerA.sendAMessage();
}

I get a ClassCastException like this:

java.lang.ClassCastException: org.springframework.integration.channel.PublishSubscribeChannel cannot be cast to org.springframework.messaging.MessageChannel

And when I change messageChannel in BrokerA to the type of PublishSubscribeChannel, it will complain about PublishSubscribeChannel doesn't have a method called send().

This really baffles me. Any suggestions or comments? Thank you!

Upvotes: 2

Views: 529

Answers (4)

Gary Russell
Gary Russell

Reputation: 174664

You have an old version of Spring Integration on the classpath; MessageChannel etc was moved from o.s.integration... to o.s.messaging in Spring 4.0.

You need to use Spring Integration 4.x.

Upvotes: 1

Rakshit P R Vashishta
Rakshit P R Vashishta

Reputation: 66

Try doing an explicit cast in the return statement of brokerChannel1() in BrokerConfiguration.

Upvotes: 0

dgofactory
dgofactory

Reputation: 348

I ran your code on my environment with last spring boot version without any version specification about spring and it's working just right, the only error is on

MessageBuilder.withPayload("This is a message!") it should be MessageBuilder.withPayload("This is a message!").build()

And I verified using org.springframework.integration.support.MessageBuilder.

Upvotes: 0

Andres
Andres

Reputation: 10725

Check your classpath, probably you have duplicated jars.

Upvotes: 1

Related Questions