曹耘豪的博客

Spring自定义starter

  1. 引入依赖
  2. 编写目标Bean类
  3. 编写Properties类
  4. 编写AutoConfiguration类
  5. 编写spring.factories
  6. 打包后使用
  7. 参考

引入依赖

1
2
3
4
dependencies {
implementation 'org.springframework.boot:spring-boot-autoconfigure:2.3.2.RELEASE'
annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor:2.3.2.RELEASE'
}

编写目标Bean类

1
2
3
4
5
public class UserService {
@Getter
@Setter
String username;
}

编写Properties类

1
2
3
4
5
6
@ConfigurationProperties(prefix = "com.cyh.user")
public class UserProperties {
@Getter
@Setter
private String username;
}

编写AutoConfiguration类

1
2
3
4
5
6
7
8
9
10
@Configuration
@EnableConfigurationProperties(UserProperties.class)
public class UserAutoConfiguration {
@Bean
public UserService userService(UserProperties userProperties) {
UserService userService = new UserService();
userService.setUsername(userProperties.getUsername());
return userService;
}
}

编写spring.factories

resources新建文本文件META-INF/spring.factories

1
2
org.springframework.boot.autoconfigure.EnableAutoConfiguration = \
com.cyh.user.UserAutoConfiguration

打包后使用

项目引用该jar包后可直接使用@Autowired自动注入

参考

   /