思想:主要是EnableAutoConfiguration在启动的时候会扫描spring.factories并加载
1在resource下面新建META-INF/spring.factories
2在spring.factories中添加自动装载的类
3其他项目引用既OK
1.新建一个starter的Maven项目A,pom文件修改
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.6.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example.start</groupId> <artifactId>spring-boot-starter-demo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>demo</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <!--支持读取配置文件属性--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>
<!--需要改jar 才会自动加载enableautoconfiguration-->
<dependency>
<groupId>org.springframework.boot</groupId> <artifactId>spring-boot-autoconfigure</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
2.新建resource文件,META-INF/spring.factories文件
多个可这样写:(\表示换行可读取到属性)(,多个属性分割)
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.example.start.demo.service.MyHelloConfiguration,\
com.example.start.demo.service.MyHelloConfiguration
3.新建MyHelloConfiguration配置类
@Configuration
public class MyHelloConfiguration {
//当不存在HelloService时加载
@Bean
@ConditionalOnMissingBean(HelloService.class)
public HelloService test() {
HelloService helloService = new HelloService();
helloService.setMsg("world");
return helloService;
}
}
public class HelloService { private String msg; public void setMsg(String msg) { this .msg = msg; } public String sayHello() { return "hello" + msg; } }
4.在IDEA中Maven下执行install将jar包发布到本地仓库
5在项目B中引入项目A新建的spring-boot-starter-demo.jar
<dependency>
<groupId>com.example.start</groupId>
<artifactId>spring-boot-starter-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
6项目B引用测试结果:
项目B调用项目A的service
启动项目B设置application.properties文件debug=true,启动输出结果:
测试运行结果: