public interface FormatProcessor {
public <T> String format(T obj);
}
public class JsonFormatProcessor implements FormatProcessor{
@Override
public <T> String format(T obj) {
return "JsonFormatProcessor:" + JSON.toJSONString(obj);
}
}
public class StringFormatProcessor implements FormatProcessor{
@Override
public <T> String format(T obj) {
return "StringFormatProcessor:" + Objects.toString(obj);
}
}
public class HelloFormatTemplate {
private FormatProcessor formatProcessor;
private HelloProperties helloProperties;
public HelloFormatTemplate(FormatProcessor formatProcessor, HelloProperties helloProperties) {
this.formatProcessor = formatProcessor;
this.helloProperties = helloProperties;
}
public <T> String doFormat(T obj) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("begin:Execute format:").append("<br/>");
stringBuilder.append("HelloProperties:").append(formatProcessor.format(helloProperties.getInfo())).append("<br/>");
stringBuilder.append("Object format result:").append(formatProcessor.format(obj)).append("\n");
return stringBuilder.toString();
}
}
@Configuration
public class FormatAutoConfiguration {
@ConditionalOnMissingClass(value = "com.alibaba.fastjson.JSON")
@Primary
@Bean
public FormatProcessor stringFormat() {
return new StringFormatProcessor();
}
@ConditionalOnClass(name = "com.alibaba.fastjson.JSON")
@Bean
public FormatProcessor jsonFormat() {
return new JsonFormatProcessor();
}
}
@ConfigurationProperties(prefix = HelloProperties.HELLO_FORMAT_PREFIX)
public class HelloProperties {
public static final String HELLO_FORMAT_PREFIX="moremind.hello.format";
private Map<String, Object> info;
public Map<String, Object> getInfo() {
return info;
}
public void setInfo(Map<String, Object> info) {
this.info = info;
}
}
@Import(FormatAutoConfiguration.class)
@EnableConfigurationProperties(HelloProperties.class)
@Configuration
public class HelloAutoConfiguration {
@Bean
public HelloFormatTemplate helloFormatTemplate(FormatProcessor formatProcessor, HelloProperties helloProperties) {
return new HelloFormatTemplate(formatProcessor, helloProperties);
}
}
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
cn.moremind.formatspringbootstarter.auto.HelloAutoConfiguration
添加spring加载时自动装配的bean。