自定义starter
maven 依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<!-- 能够给开发者引入该jar包后 有一定提示 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency>
核心代码
@ConfigurationProperties(prefix = "mayikt")
public class TokenProperties {
private String tokenRedisHost;
private String tokenRedisPwd;
}
@Configuration
@EnableConfigurationProperties(TokenProperties.class)
public class TokenAutoConfiguration {
@Bean
public TokenService tokenService() {
return new TokenService();
}
}
public class TokenService {
@Autowired
private TokenProperties tokenProperties;
public String getToken() {
System.out.println("模拟生成token");
return tokenProperties.getTokenRedisHost() + "," + tokenProperties.getTokenRedisPwd();
}
}
SPI
META-INF/spring.factories 内容:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.mayikt.utils.TokenAutoConfiguration
SPI 是 Java 提供的一种服务加载方式