自定义启动器
1 功能描述
场景:抽取聊天机器人场景,它可以打招呼。
效果:任何项目导入此starter都具有打招呼功能,并且问候语中的人名需要可以在配置文件中修改
- 创建
自定义starter项目,引入spring-boot-starter基础依赖 - 编写模块功能,引入模块所有需要的依赖。
- 编写
xxxAutoConfiguration自动配置类,帮其他项目导入这个模块需要的所有组件 - 编写配置文件
META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports指定启动需要加载的自动配置 - 其他项目引入即可使用
2 自定义启动器
2.1 创建自定义启动器工程导入依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.5</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 导入配置处理器,配置文件自定义的properties配置都会有提示-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
2.2 创建属性类及业务类
(1)RobotProperties
@ConfigurationProperties(prefix = "robot") //此属性类和配置文件指定前缀绑定
@Component
@Data
public class RobotProperties {
private String name;
private String age;
private String email;
}
(2)RobotService
@Service
public class RobotService {
@Autowired
RobotProperties robotProperties;
public String sayHello(){
return "你好:名字:【"+robotProperties.getName()+"】;年龄:【"+robotProperties.getAge()+"】";
}
}
2.3 提取公共配置类
自己写一个
RobotAutoConfiguration,给容器中导入这个场景需要的所有组件
- 为什么这些组件默认不会扫描进去?
- starter所在的包和 引入它的项目的主程序所在的包不是父子层级
别人引用这个
starter,直接导入这个RobotAutoConfiguration,就能把这个场景的组件导入进来
//给容器中导入Robot功能要用的所有组件
@Import({RobotProperties.class, RobotService.class})
@Configuration
public class RobotAutoConfiguration {}
2.4 自定义@EnableXXX机制(可选)
他人引入
starter可以使用@EnableRobot开启自动配置功能
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
@Import(RobotAutoConfiguration.class)
public @interface EnableRobot {}
2.5 使用配置文件开启自动配置
META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports 文件中编写好我们自动配置类的全类名即可
- com.mytest.RobotAutoConfiguration
- 如引入自定义启动器工程与当前自定义启动器不在同一目录下:需要将spring_starter项目进行install,并导入当前工程操作
3 应用自定义启动器
3.1 在使用的工程中引入自定义启动器项目依赖
<dependency>
<groupId>com.mytest</groupId>
<artifactId>spring_starter</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
3.2 使用@EnableRobot注解开启自动配置
- application.properties配置文件
robot.name=lucy
robot.age=20
robot.email=java@mytest.com
- 启动类代码
@SpringBootApplication
@EnableRobot
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
3.3 Controller中测试
启动测试,访问路径:http://localhost:8080/robot/hello
@RestController
public class HelloController {
@Autowired
private RobotService robotService;
@GetMapping("/hello")
public String hello(){
System.out.println(robotService.sayHello());
return "Hello,Spring Boot 3!";
}
}