说明:
Service类是自定义的一个类,该类中有成员变量prefix和suffix,成员方法doService,该方法的作用是对入参value加上前缀后prefix和后缀suffix后返回。
ServiceProperties类的作用是将配置文件application.yml中以my.service开头的配置读入。
ServiceAutoConfiguration类的作用是使ServiceProperties生效,并将一个Service的实例注入IoC容器。
目标:
别的Spring Boot工程引用这个starter,通过自动装配来使用Service
Gitee地址
autoconfigure包下存放ServiceAutoConfiguration.java
、ServiceProperties.java
,service包下存放Service
@Data
@AllArgsConstructor
public class Service {
private String prefix;
private String suffix;
public String doService(String value) {
return prefix + value + suffix;
}
}
@Data
@ConfigurationProperties(prefix = "my.service")
public class ServiceProperties {
private String prefix;
private String suffix;
}
@Configuration
@ConditionalOnClass(Service.class) // 类路径下存在Service时才生效
@EnableConfigurationProperties(ServiceProperties.class) // 使ServiceProperties生效
public class ServiceAutoConfiguration {
@Autowired
private ServiceProperties serviceProperties;
@Bean
@ConditionalOnMissingBean // 使这个bean成为单例模式
@ConditionalOnProperty(
prefix = "my.service",
value = "enable",
havingValue = "true"
) // 当配置文件中my.service.enable的值为true时才生效
public Service service() {
return new Service(serviceProperties.getPrefix(), serviceProperties.getSuffix());
}
}
resources下新建一个文件META-INF,在META-INF下新建文件spring.factories
(必须叫这个名!!!)
# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.example.myspringbootstarter.autoconfigure.ServiceAutoConfiguration
有两种方式,任选一种即可
pom.xml:
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
<configuration>
<skip>trueskip>
configuration>
plugin>
plugins>
build>
重要!spring boot工程创建时没有
这一行,install前需要加入这一行设置!否则打出来的包中会多一个BOOT-INF文件夹,导致别的工程无法引用我们的类
pom.xml:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-compiler-pluginartifactId>
<configuration>
<source>1.8source>
<target>1.8target>
configuration>
plugin>
plugins>
build>
maven手动安装命令:
mvn install:install-file -DgroupId=com.example -DartifactId=my-spring-boot-starter -Dversion=1.0 -Dpackaging=jar -Dfile=E:\my-spring-boot-starter.jar
在其他工程中:
<dependency>
<groupId>com.examplegroupId>
<artifactId>my-spring-boot-starterartifactId>
<version>0.0.1-SNAPSHOTversion>
dependency>
my:
service:
enable: true
prefix: pp
suffix: ss
在controller中测试:
@RestController
public class UserController {
@Autowired
private Service service;
@RequestMapping("/service")
public String service() {
return service.doService("haha");
}
}
通过浏览器访问,返回ppp-haha-sss