引入依赖
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' }
|
spring-boot-configuration-processor用于生成spring-configuration-metadata.json
编写目标Bean类
1 2 3 4 5
| public class UserService { @Getter @Setter String username; }
|
编写Properties类
- 用于在spring配置(如
application.yml)里进行bean的属性配置
1 2 3 4 5 6
| @ConfigurationProperties(prefix = "com.cyh.user") public class UserProperties { @Getter @Setter private String username; }
|
编写AutoConfiguration类
@EnableConfigurationProperties用于开启ConfigurationProperties
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自动注入
参考