在了解了spring boot自动配置的原理之后,我们可以尝试自己创建一个starter。
创建starter模块
创建的starter模块是一个空的jar包,里面只是做依赖管理,使用者只需将starter引入即可使用。
创建一个starter模块,命名为monkey1024-spring-boot-starter
在starter模块中加入autoconfigure模块的依赖
<!--autoconfigure自动配置模块-->
<dependency>
<groupId>com.monkey1024</groupId>
<artifactId>monkey1024-spring-boot-starter-autoconfigurer</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
创建autoconfigure模块
创建一个autoconfigure模块,命名为monkey1024-spring-boot-autoconfigure
添加下面依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!--为properties类生成相应的json文件-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
创建UserProperties类
@ConfigurationProperties(prefix = "monkey1024.user")
public class UserProperties {
private String name;
private String password;
//get和set略
}
创建UserService类
public class UserService {
private UserProperties userProperties;
public UserService(UserProperties userProperties) {
this.userProperties = userProperties;
}
public UserService() {}
public boolean validate() {
if ("admin".equals(userProperties.getName()) && "123".equals(userProperties.getPassword())) {
return true;
}
return false;
}
}
创建UserAutoConfiguration类
@Configuration
@ConditionalOnWebApplication//在web应用下启用
@EnableConfigurationProperties(UserProperties.class)//开启配置类
public class UserAutoConfiguration {
@Autowired
private UserProperties userProperties;
@Bean
@ConditionalOnMissingBean(UserService.class)//当容器中不存在该对象的时候创建
public UserService addUserService() {
return new UserService(userProperties);
}
}
创建spring.factories文件
根据之前源码分析,我们需要在resources下创建META-INF文件夹,在该文件夹下创建spring.factories文件,里面内容如下:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.monkey1024.UserAutoConfiguration
创建测试模块
创建测试web模块将上面的starter依赖导入。在配置文件中添加下面内容:
monkey1024.user.name=admin
monkey1024.user.password=123
创建controller
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/validate")
public String validate() {
boolean validate = userService.validate();
return validate + "";
}
}
在浏览器中发出请求即可看到返回true;