springboot自定义starter并上传至公网调用
1.目录结构
2.新建DemoProperties实体类
package com.focusmedia.starter.Demo.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* 在.properties中需要配置的字段
* 配置示例:
* demo.sayWhat=hello
* demo.toWho=wshy
*
* @title: DingProperties
* @Author: wshy
*/
//将实体类注册为bean
@Component
//将实体类与properties配置文件对应
@ConfigurationProperties(prefix = "demo")
public class DemoProperties {
private String sayWhat;
private String toWho;
public String getSayWhat () {
return sayWhat;
}
public void setSayWhat (String sayWhat) {
this.sayWhat = sayWhat;
}
public String getToWho () {
return toWho;
}
public void setToWho (String toWho) {
this.toWho = toWho;
}
}
3.新建DemoService类
package com.focusmedia.starter.Demo.service;
/**
* 描述:随便定义一个Service
* service在config中进行配置注入
* @Author wshy
* @Version V1.0
**/
public class DemoService {
public String sayWhat;
public String toWho;
public DemoService(String sayWhat, String toWho){
this.sayWhat = sayWhat;
this.toWho = toWho;
}
public String say(){
return this.sayWhat + "! " + toWho;
}
}
4.新建DemoConfig配置类
package com.focusmedia.starter.Demo.config;
import com.focusmedia.starter.Demo.properties.DemoProperties;
import com.focusmedia.starter.Demo.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* 描述:配置类
*
* @Author wshy
* @Version V1.0
**/
@Configuration
@EnableConfigurationProperties(DemoProperties.class)
//条件注解,用于控制配置类是否生效
@ConditionalOnProperty(
prefix = "demo", //配置文件前缀
name = "isopen", //配置的名字
havingValue = "true"//与配置中对比的对比值,当两个值想通过返回true,配置类生效
)
//条件注解,作用在类上,只有在classpath包含DemoService时,类DemoConfig中的所有@bean标注的方法才可以注入容器
@ConditionalOnClass(DemoService.class)
public class DemoConfig {
@Autowired
private DemoProperties demoProperties;
@Bean(name = "demo")
public DemoService demoService(){
return new DemoService(demoProperties.getSayWhat(), demoProperties.getToWho());
}
}
5.新建spring.factories
在resource下面新建MATE-INF文件夹,并新建spring.factories配置文件
#-------starter自动装配---------
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.focusmedia.starter.Demo.config.DemoConfig
6.上传到git
7.Jitpack生成maven依赖
https://jitpack.io/#com.gitee.wsy-xzp/ding-spring-boot-starter/0.0.3
8.其他springboot服务中调用
9.测试调用
1.application.yml中加入starter需要的配置信息
2.启动服务,并调用接口测试
demo地址:ding-sprig-boot-starter