I am trying to refactor my code that, among other things, returns a message depending on a parameter typeSignature
.
The code below is the original working code (without the irrelevant parts) :
@Component
public class AuditUtil {
@Autowired
@Qualifier("messages")
private ReloadableConfig conf;
public Audit getTrace(int typeSignature, Order order) throws ParseException{
Audit audit = new Audit();
audit.setLabel(createMessage(typeSignature, order));
return audit;
}
private String createMessage(int typeSignature, Order order) {
List<Object> params = new ArrayList<>();
params.add("canal");
params.add(order.getId());
if(typeSignature == 1){
return MessageFormat.format(conf.getPropertyStr("message.simple.signature"), params.toArray());
} else if(typeSignature == 2){
return MessageFormat.format(conf.getPropertyStr("message.premiere.signature"), params.toArray());
} else if(typeSignature == 3){
return MessageFormat.format(conf.getPropertyStr("message.seconde.signature"), params.toArray());
}
}
}
I wanted to try the command pattern, so I did that (I'll show only 1 concrete subclass of SignatureMessageBuilder
):
@Component
public class AuditUtil {
static Map<Integer, SignatureMessageBuilder> signatureCommandMap;
static {
signatureCommandMap = new HashMap<>();
signatureCommandMap.put(1, new SimpleSignatureMessageBuilder());
signatureCommandMap.put(2, new FirstSignatureMessageBuilder());
signatureCommandMap.put(3, new SecondSignatureMessageBuilder());
}
@Autowired
@Qualifier("messages")
private ReloadableConfig conf;
public Audit getTrace(int typeSignature, Order order) throws ParseException{
Audit audit = new Audit();
audit.setLabel(createMessage(typeSignature, order));
return audit;
}
private String createMessage(int typeSignature, Order order) {
List<Object> params = new ArrayList<>();
params.add("canal");
params.add(order.getId());
return signatureCommandMap.containsKey(typeSignature) ? signatureCommandMap.get(typeSignature).buildMessage() : "";
}
}
public abstract class SignatureMessageBuilder {
protected ReloadableConfig conf;
@Autowired
public final void setConfig(@Qualifier("messages") ReloadableConfig conf) {
this.conf = conf;
}
public abstract String buildMessage();
// ommitted common protected methods for subclasses
}
@Component
public class SimpleSignatureMessageBuilder extends SignatureMessageBuilder {
private String template;
@Override
public String buildMessage() {
template = conf.getPropertyStr("message.simple.signature");
return template;
}
}
It doesn't work : I get a NullPointerException
in the SimpleSignatureMessageBuilder.buildMessage()
because conf
is null.
I've also tried to put the signatureCommandMap
initialization in a AuditUtil
constructor, conf
is still null.
What am I doing wrong ?