sprintboot3 自定义 starter 和 实现完全自动配置
目录结构
创建一个空的 Spring Initializr 项目 boot3-08-robot-starter,删除主入口类,目录结构如下

注意:annotation 包不需要,该包是用来使用@EnableXxx机制
代码
pom.xml 添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- 导入配置处理器,配置文件自定义的properties配置都会有提示 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
RobotController
@RestController
public class RobotController {
@Autowired
RobotService robotService;
@GetMapping("/robot/hello")
public String sayHello(){
String s = robotService.sayHello();
return s;
}
}
RobotProperties
@ConfigurationProperties(prefix = "robot") // 此属性类和配置文件指定前缀绑定
@Component
@Data
public class RobotProperties {
private String name;
private String age;
private String email;
}
RobotAutoConfiguration
@Import({RobotController.class, RobotProperties.class, RobotService.class})
@Configuration
public class RobotAutoConfiguration {
}
在 resources 文件夹下依次创建文件夹,META-INF,spring, 在创建一个文件,名字为
org.springframework.boot.autoconfigure.AutoConfiguration.imports
内容如下
com.klvchen.boot3.starter.robot.RobotAutoConfiguration
测试
其他项目导入依赖
pom.xml
<dependency>
<groupId>com.klvchen</groupId>
<artifactId>boot3-08-robot-starter</artifactId>
<version>0.0.1-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<!-- 导入配置处理器,配置文件自定义的properties配置都会有提示 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
在 application.properties 文件中添加下面内容并启动项目
robot.name=klvchne
robot.age=24
robot.email=klvchen@qq.com
浏览器访问结果如下:


浙公网安备 33010602011771号