首先明确:starter是一种集成(自动装配)
starter命名规则:
spring-boot-starter-{name}
{name}-spring-boot-starter [mybatis-spring-boot-starter]
自定义一个格式化组件(类似于RestTemplate):
//接口及两个实现类
package org.demo.starter.format;
public interface FormatProcessor {
<T> String format(T obj);
}
import com.alibaba.fastjson.JSON;
public class JsonFormatProcessor implements FormatProcessor {
@Override
public <T> String format(T obj) {
String json = JSON.toJSONString(obj, true);
return json;
}
}
public class StringFormatProcessor implements FormatProcessor {
@Override
public <T> String format(T obj) {
return Objects.toString(obj, "null");
}
}
格式化实现配置类
@Configuration
public class FormatProcessorConfiguration {
@ConditionalOnMissingClass("com.alibaba.fastjson.JSON")
@Bean
@Primary
public FormatProcessor stringFormatProcessor() {
return new StringFormatProcessor();
}
@Bean
@ConditionalOnClass(JSON.class)
public FormatProcessor jsonFormatProcessor() {
return new JsonFormatProcessor();
}
}
模板对象
import java.util.Optional;
public class DefaultFormatTemplate {
private FormatProcessor formatProcessor;
private FormatProperties properties;
public DefaultFormatTemplate(FormatProcessor formatProcessor, FormatProperties properties) {
this.formatProcessor = formatProcessor;
this.properties = properties;
}
public String format(Object target) {
System.out.println(properties);
return Optional.ofNullable(formatProcessor)
.orElseThrow(() -> new RuntimeException("没有合适的格式化工具"))
.format(target);
}
}
//仅测试自动属性装配
@ConfigurationProperties(prefix = "my.format")
public class FormatProperties {
private String name;
private Integer flag;
private Map<String, Object> info;
//getter and setter ....
}
模板配置类
//此处静态引入依赖的Bean配置类
@Import({FormatProcessorConfiguration.class, FormatProperties.class})
@Configuration
public class FormatTemplateConfiguration {
@Bean
public DefaultFormatTemplate defaultFormatTemplate(FormatProcessor formatProcessor, FormatProperties properties) {
return new DefaultFormatTemplate(formatProcessor, properties);
}
}
在META-INF/spring.factories文件中配置
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.demo.starter.autoconfiguration.FormatTemplateConfiguration
在其他项目中引入该工程木块即可使用自动注入DefaultFormatTemplate
@RestController
@Slf4j
public class HelloController {
@Autowired
private DefaultFormatTemplate formatTemplate;
@GetMapping("/format")
public Object format() {
User user = new User();
user.setId(1);
user.setUsername("leber");
user.setPassword("123456");
String format = formatTemplate.format(user);
log.info("格式化对象为:\n{}", format);
return format;
}
}