仿照spring的规范,artifact命名为xxx-spring-boot-starter
这里只作为测试,就按最低的需求来只勾选如下三个
lombok、spring-boot-configuration-processor、spring-boot-autoconfigure
默认生成的项目结构如下
因为我们项目最终是给其他项目依赖使用的,所以可以删除一些不需要用到的文件
删除默认生成的启动类
删除test文件
删除pom中多于的配置,主要是关于测试和打包成可启动类的
我这配置文件application.properties也没用上,也删了
在resource文件夹下新建META-INF文件夹
在META-INF文件夹下新建spring.factories备用
最终项目结构如下
注意检查! spring.factories文件的颜色,如果颜色不对,说明配置有问题,会影响后面的引用!!!
新建HelloProperties,用于定义配置信息,主要包括定义配置文件的前缀和key
package cn.hello;import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;@ConfigurationProperties(prefix = "spring.hello")//定义配置文件前缀
@Data
public class HelloProperties {private String username;//配置的keyprivate String age;private String address;
}
新建HelloService,主要用于处理具体的业务
package cn.hello;import org.springframework.stereotype.Component;@Component
public class HelloService {private HelloProperties log2esProperties;public HelloService(HelloProperties log2esProperties) {this.log2esProperties = log2esProperties;}public void sayHello() {System.out.println(log2esProperties);}
}
关键!配置自动装配
package cn.hello;import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
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;import javax.annotation.Resource;@Configuration
@EnableConfigurationProperties(HelloProperties.class)
@ConditionalOnClass(HelloService.class)
@ConditionalOnProperty(prefix = "spring.hello", value = "enabled", matchIfMissing = true)
public class HelloServiceAutoConfiguration {@Resourceprivate HelloProperties log2esProperties;@ConditionalOnMissingBean(HelloService.class)@Beanpublic HelloService log2esService(){return new HelloService(log2esProperties);}
}
以便HelloServiceAutoConfiguration能被spring识别并管理
org.springframework.boot.autoconfigure.EnableAutoConfiguration=cn.hello.HelloServiceAutoConfiguration
一切准备就绪,运行 mvn install
将项目打成一个jar包
随便挑选一个springboot项目,在其resources下新建一个lib文件夹,记得右键lib,
Mark Directory as Excluded
然后再pom中引用
cn.hello hello-spring-boot-starter 0.0.1-SNAPSHOT system ${pom.basedir}/src/main/resources/lib/hello-spring-boot-starter-0.0.1-SNAPSHOT.jar
具体业务类中引用
@Autowiredprivate HelloService helloService;@GetMapping("/helloService")//@SysOpLogAnnotation(content = "helloService", operation = "helloService")public JsonResult esService() {helloService.sayHello();JsonResult jsonResult = new JsonResult(true);jsonResult.put("article",null);return jsonResult;}
yml配置安排一下
spring:hello:username: pdage: 20address: 卡塔尔多哈
启动,测试