starter会把所有用到的依赖都给包含进来,避免了开发者自己去引入依赖所带来的麻烦。
虽然不同的starter实现起来各有差异,但是他们基本上都会使用到两个相同的内容:ConfigurationProperties和AutoConfiguration。
Starters 是一组可以让你很方便在应用增加的依赖关系描述符的集合。或者可以这样理解,平时我们开发的时候很多情况下都会有一个模块依赖另一个模块,这个时候我们一般都是采用 maven 的模块依赖,进行模块的依赖
pom 依赖
1 MyJsonAutoConfiguration
package com.gupao.starter.demo.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConditionalOnClass(MyJsonService.class)
@EnableConfigurationProperties(MyJsonProperties.class)
public class MyJsonAutoConfiguration {
@Autowired
private MyJsonProperties myJsonProperties;
@Bean
@ConditionalOnMissingBean(MyJsonService.class)
public MyJsonService myJsonService() {
MyJsonService myJsonService = new MyJsonService();
myJsonService.setName(myJsonProperties.getName());
return myJsonService;
}
}
2 MyJsonProperties
package com.gupao.starter.demo.service;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix ="gp.json")
public class MyJsonProperties {
public static final String DEFAULT_NAME = "gp";
private String name = DEFAULT_NAME;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
3 MyJsonService
package com.gupao.starter.demo.service;
import com.alibaba.fastjson.JSON;
public class MyJsonService {
private String name;
public String objToJson(Object obj) {
return getName() + JSON.toJSONString(obj);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
自动装配
然后我们通过运行mvn install命令,将这个项目打包成 jar 部署到本地仓库中,提供让另一个服务调用。