说明:
Service类是自定义的一个类,该类中有成员变量prefix和suffix,成员方法doService,该方法的作用是对入参value加上前缀后prefix和后缀suffix后返回。
ServiceProperties类的作用是将配置文件application.yml中以my.service开头的配置读入。
ServiceAutoConfiguration类的作用是使ServiceProperties生效,并将一个Service的实例注入IoC容器。
目标:
别的Spring Boot工程引用这个starter,通过自动装配来使用Service
1.编写程序
java部分
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部分
resources下新建一个文件META-INF,在META-INF下新建文件spring.factories
(必须叫这个名!!!)
# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.example.myspringbootstarter.autoconfigure.ServiceAutoConfiguration
2.install打包安装到本地仓库
有两种方式,任选一种即可
方式一:通过maven的springboot插件打包(便捷、推荐)
pom.xml:
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<!--
重要!spring boot工程创建时没有这一行,install前需要加入这一行设置!
否则打出来的包中会多一个BOOT-INF文件夹,导致别的工程无法引用我们的类
-->
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
重要!spring boot工程创建时没有<skip>true</skip>
这一行,install前需要加入这一行设置!否则打出来的包中会多一个BOOT-INF文件夹,导致别的工程无法引用我们的类
方式二:通过maven的apache maven插件打包
pom.xml:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
也可以通过IDEA手动打包后,再用maven手动安装到本地仓库
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
3.其他工程通过maven引入
在其他工程中:
- pom.xml:
<dependency>
<groupId>com.example</groupId>
<artifactId>my-spring-boot-starter</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
- application.yml:
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