Skip to content
Advertisement

Send data object using key

I want to create something like quick switch to send Java object based on Key. I tried this:

private MessageProcessor defaultProcessor;
private Map<String, MessageProcessor> processors;

MessageProcessor messageProcessor = processors.getOrDefault(payloadObject.getName(), defaultProcessor);
public ResponseObject process(@RequestBody PayloadObject payloadObject)
{
   MessageProcessor messageProcessor = processors.getOrDefault(payloadObject.getName(), defaultProcessor);
   return messageProcessor.processMessage(payloadObject);
}


public interface MessageProcessor {

    ResponseObject processMessage(PayloadObject payloadObject);
}

// if we send a key first send to this class the payload

@Component("first")
public class FirstService implements MessageProcessor {

    @Override
    public ResponseObject processMessage(PayloadObject payloadObject) {
        return new ResponseObject("first payload");
    }
}

Full code example: https://github.com/rcbandit111/Code_Switch_Select_POC/blob/main/src/main/java/org/poc/PocController.java

Is it possible to use @Service("first") instead of @Component("first") and also how I can make the code much more simple?

Advertisement

Answer

based on your source code, it can be simplified by using Class itself.

Here is an example of some Spring HTTP Converters for Resource class: https://github.com/spring-projects/spring-framework/blob/main/spring-web/src/main/java/org/springframework/http/converter/ResourceHttpMessageConverter.java#L74

The idea is that Spring can easily create a POJO for you from JSON/XML/etc and in runtime you can get its class myvar.getClass() to determine what OOP Strategy to choose.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement