Spring源码学习三

手写Starter
我们通过手写Starter来加深对于自动装配的理解
1.创建一个Maven项目,quick-starter
定义相关的依赖

<dependency>
	<groupId>org.springframework.bootgroupId>
	<artifactId>spring-boot-starterartifactId>
	<version>2.1.6.RELEASEversion>
dependency>
<dependency>
	<groupId>com.alibabagroupId>
	<artifactId>fastjsonartifactId>
	<version>1.2.56version>
	
	<optional>trueoptional>
dependency>

2.定义Formate接口
定义的格式转换的接口,并且定义两个实现类

public interface FormatProcessor {
	/**
	* 定义一个格式化的方法
	* @param obj
	* @param 
	* @return
	*/
	<T> String formate(T obj);
}
public class JsonFormatProcessor implements FormatProcessor {
	@Override
	public <T> String formate(T obj) {
		return "JsonFormatProcessor:" + JSON.toJSONString(obj);
	}
}
public class StringFormatProcessor implements FormatProcessor {
	@Override
	public <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")
	@Bean
	public 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("
"
); builder.append("Object format result:" ).append(formatProcessor.formate(obj)); return builder.toString(); } }

再就是整合到SpringBoot中去的Java配置类

@Configuration
@Import(FormatAutoConfiguration.class)
public class HelloAutoConfiguration {
	@Bean
	public HelloFormatTemplate helloFormatTemplate(FormatProcessor
	formatProcessor){
		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.examplegroupId>
	<artifactId>format-spring-boot-starterartifactId>
	<version>1.0-SNAPSHOTversion>
dependency>

在controller中使用

@RestController
public class UserController {
	@Autowired
	private HelloFormatTemplate helloFormatTemplate;
	@GetMapping("/format")
	public String format(){
		User user = new User();
		user.setName("BoBo");
		user.setAge(18);
		return helloFormatTemplate.doFormat(user);
	}
}

你可能感兴趣的:(学习,spring,学习,java)