自定义 Spring Boot starter
写一个简单的工程,当作自定义的框架
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;
}
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.suffix;
}
}
package com.southwind.config;
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 AutoConfigure {
@Autowired
private ServiceProperties serviceProperties;
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(
prefix = "southwind.service",
value = "enable",
havingValue = "true"
)
public Service service(){
return new Service(serviceProperties.getPrefix(), serviceProperties.getSuffix());
}
}
spring.factories
# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.southwind.config.AutoConfigure
打成 jar 包
将 jar 导入 Maven 本地仓库
mvn install:install-file -DgroupId=com.southwind -DartifactId=003_starter -Dversion=1.0 -Dpackaging=jar -Dfile=D:\WorkSpace\IdeaProjects\003_myspringbootstarter\out\artifacts\003_myspringbootstarter_jar\003_myspringbootstarter.jar
Spring Boot 引用
<dependency>
<groupId>com.southwind</groupId>
<artifactId>003_starter</artifactId>
<version>1.0</version>
</dependency>
1、创建一个工程 starter工具(要导入 Spring Boot 工程中),读取 application.yml 中的配置信息(prefix,suffix),生成一个 service 对象,业务是对传入的参数进行处理:prefix+参数+suffix,返回。
2、将 starter 工具导入 Spring Boot 工程中,直接使用(自动装配)。