I am currently working with SpringBoot JMS and I am a bit confused.
When I use the RestTemplate on the web the contract between sender and receiver is the JSON format. It doesn't matter how the sender generates the JSON (or from which class). That means the sender does not have to have the same DTO class as the receiver.
I assumed that the same would apply to JMS. Unfortunately, the sender and the receiver must have exactly the same class. I find that somehow impractical.
Of course I could just send a string (containing a JSON) on both sides. But I actually expect Spring to do this by itself. To keep the code simple I just want to tell Spring "here send this object as JSON". And on the other side just "parse that JSON into this object".
When I run the example below I get the following error message: org.springframework.messaging.converter.MessageConversionException: Cannot convert from [com.example.demo.MyObject2] to [com.example.demo.MyObject] for org.springframework.jms.listener.adapter.AbstractAdaptableMessageListener$MessagingMessageConverterAdapter$LazyResolutionMessage@3c60bcf
Did I just not understand the principle or is my thought so absurd that it is not the "normal" way and you have to do a lot by hand?
Here is my code (Note: MyObject
and MyObject2
have both just one attribute (String key
)):
@SpringBootApplication
@EnableJms
public class DemoApplication implements CommandLineRunner {
@Autowired
private JmsTemplate jmsTemplate;
public static void main(String[] args) throws IOException {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
public MessageConverter jacksonJmsMessageConverter() {
MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
converter.setTargetType(MessageType.TEXT);
converter.setTypeIdPropertyName("_type");
return converter;
}
@JmsListener(destination = "test")
public void test(MyObject dto) {
System.out.println(dto);
}
@Override
public void run(String... args) throws Exception {
MyObject2 obj = new MyObject2();
obj.setKey("Test me");
jmsTemplate.convertAndSend("test", obj);
}
}
See
/**
* Specify mappings from type ids to Java classes, if desired.
* This allows for synthetic ids in the type id message property,
* instead of transferring Java class names.
* <p>Default is no custom mappings, i.e. transferring raw Java class names.
* @param typeIdMappings a Map with type id values as keys and Java classes as values
*/
public void setTypeIdMappings(Map<String, Class<?>> typeIdMappings) {
on the converter.
On sending side, map MyObject.class
from myObject
and on the consumer side, map myObject
to MyOtherObject.class
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.