手写Starter
 我们通过手写Starter来加深对于自动装配的理解
 1.创建一个Maven项目,quick-starter
 定义相关的依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId><version>2.1.6.RELEASE</version>
</dependency>
<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.56</version><!-- 可选 --><optional>true</optional>
</dependency>
 
2.定义Formate接口
 定义的格式转换的接口,并且定义两个实现类
public interface FormatProcessor {/*** 定义一个格式化的方法* @param obj* @param <T>* @return*/<T> String formate(T obj);
}
 
public class JsonFormatProcessor implements FormatProcessor {@Overridepublic <T> String formate(T obj) {return "JsonFormatProcessor:" + JSON.toJSONString(obj);}
}
 
public class StringFormatProcessor implements FormatProcessor {@Overridepublic <T> String formate(T obj) {return "StringFormatProcessor:" + obj.toString();}
}
 
3.定义相关的配置类
 首先定义格式化加载的Java配置类
@Configuration
public class FormatAutoConfiguration {@ConditionalOnMissingClass("com.alibaba.fastjson.JSON")@Bean@Primary // 优先加载public FormatProcessor stringFormatProcessor(){return new StringFormatProcessor();}@ConditionalOnClass(name="com.alibaba.fastjson.JSON")@Beanpublic FormatProcessor jsonFormatProcessor(){return new JsonFormatProcessor();}
}
 
定义一个模板工具类
public class HelloFormatTemplate {private FormatProcessor formatProcessor;public HelloFormatTemplate(FormatProcessor processor){this.formatProcessor = processor;}public <T> String doFormat(T obj){StringBuilder builder = new StringBuilder();builder.append("Execute format : ").append("<br>");builder.append("Object format result:").append(formatProcessor.formate(obj));return builder.toString();}
}
 
再就是整合到SpringBoot中去的Java配置类
@Configuration
@Import(FormatAutoConfiguration.class)
public class HelloAutoConfiguration {@Beanpublic HelloFormatTemplate helloFormatTemplate(FormatProcessorformatProcessor){return new HelloFormatTemplate(formatProcessor);}
} 
4.创建spring.factories文件
 在resources下创建META-INF目录,再在其下创建spring.factories文件
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.mashibingedu.autoconfiguration.HelloAutoConfiguration
 
install 打包,然后就可以在SpringBoot项目中依赖改项目来操作了。
 5.测试
 在SpringBoot中引入依赖
<dependency><groupId>org.example</groupId><artifactId>format-spring-boot-starter</artifactId><version>1.0-SNAPSHOT</version>
</dependency>
 
在controller中使用
@RestController
public class UserController {@Autowiredprivate HelloFormatTemplate helloFormatTemplate;@GetMapping("/format")public String format(){User user = new User();user.setName("BoBo");user.setAge(18);return helloFormatTemplate.doFormat(user);}
}