自定义简单sprin-boot-starter
自定义简单sprin-boot-starter

新建IDEA一个空项目
空项目里新建模块新建maven空项目主要为了引入自动配置包
空项目里新建模块spring-boot项目做自动配置
maven项目引入自动配置包坐标
启动项目pom
<groupId>com.xiaocheng</groupId> <artifactId>hello-spring-boot-starter</artifactId> <version>1.0</version> <dependencies> <dependency> <groupId>com.xiaocheng</groupId> <artifactId>hello-spring-boot-starter-autoconfigure</artifactId> <version>0.0.1</version> </dependency> </dependencies>
自动配置项目pom
<groupId>com.xiaocheng</groupId> <artifactId>hello-spring-boot-starter-autoconfigure</artifactId> <version>0.0.1</version> <name>hello-spring-boot-starter-autoconfigure</name> <description>hello-spring-boot-starter-autoconfigure</description> <properties> <java.version>15</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <!-- 在自定义starter的pom文件中加入如下依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> </dependencies>
@Configuration @EnableConfigurationProperties(HelloProperties.class)//加载配置类 public class HelloServiceAutoConfiguration { @Bean @ConditionalOnMissingBean(HelloService.class)//判断没有该类则把该类放入spring public HelloService helloSerivce(){ return new HelloService(); } }
@ConfigurationProperties("hello")
public class HelloProperties {
private String front;
private String queen ;
public String getFront() {
return front;
}
public void setFront(String front) {
this.front = front;
}
public String getQueen() {
return queen;
}
public void setQueen(String queen) {
this.queen = queen;
}
}
public class HelloService { @Autowired HelloProperties helloProperties; public String hello(String str) { return helloProperties.getFront() + str + helloProperties.getQueen(); } }
资源文件下新建META-INF
META-INF下建spring.factories
项目启动加载该类
# Auto Configure org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.xiaocheng.auto.HelloServiceAutoConfiguration
完成后记得maven
install发布本地仓库/deploy发布中央仓库

yaml可以 赋值


OK了

浙公网安备 33010602011771号