文章目录
- Spring Boot 自定义 Starter
- 1、自定义一个要装载的项目
- 2、创建属性读取类 ServiceProperties
- 3、创建 Service
- 4、创建自动配置类 AutoConfigration
- 5、创建 spring 工程文件
- 6、将项目打成 jar 包
- 7、jar 打包到本地仓库
- 8、配置application.yml
Spring Boot 自定义 Starter
Spring Boot Starter 启动器自动装载 bean 。
把一个完整的项目(框架)自动组装到我们的项目中
1、自定义一个要装载的项目
2、创建属性读取类 ServiceProperties
package com.southwind.properties;import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;@Data
@ConfigurationProperties(prefix = "southwind.service")
public class ServiceProperties {private String prefix;private String suffix;
}
3、创建 Service
package com.southwind.service;public class Service {private String prefix;private String suffix;public Service(String prefix, String suffix) {this.prefix = prefix;this.suffix = suffix;}public String doService(String value){return this.prefix + value + this.prefix;}}
4、创建自动配置类 AutoConfigration
package com.southwind.configuration;import com.southwind.properties.ServiceProperties;
import com.southwind.service.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.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
@ConditionalOnClass(Service.class)
@EnableConfigurationProperties(ServiceProperties.class)
public class AutoConfiguration {@Autowiredprivate ServiceProperties serviceProperties;@Bean@ConditionalOnMissingBean@ConditionalOnProperty(prefix = "southwind.service",value = "enable",havingValue = "true")public Service service(){return new Service(serviceProperties.getPrefix(),serviceProperties.getSuffix());}}
5、创建 spring 工程文件
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.southwind.configuration.AutoConfiguration
6、将项目打成 jar 包
7、jar 打包到本地仓库
mvn install:install-file -DgroupId=com.southwind -DartifactId=mystarter002 -Dversion=1.0.0 -Dpackaging=jar -Dfile=D:\WorkSpace\IdeaProjects\mystarter002\out\artifacts\mystarter002_jar\mystarter002.jar
8、配置application.yml
southwind:service:prefix: 123suffix: abcenable: true