SpringBoot自定义Start
# 实现效果
场景:抽取聊天机器人场景,它可以打招呼。 效果:任何项目导入此starter都具有打招呼功能,并且问候语中的人名需要可以在配置文件中修改
# 封装项目
- 创建自定义starter项目robot-spring-boot-start,引入spring-boot-starter基础依赖
- 编写模块功能,引入模块所有需要的依赖。
- 编写xxxAutoConfiguration自动配置类,帮其他项目导入这个模块需要的所有组件
- 在项目中导入这个start即可
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<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>
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
RobotController类
@RestController
public class RobotController {
@Autowired
RobotService robotService;
@RequestMapping("/robot/hello")
public String sayHello(){
return robotService.sayHello();
}
}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
RobotService类
public interface RobotService {
public String sayHello();
}
1
2
3
4
2
3
4
RobotServiceImpl类
@Service
public class RobotServiceImpl implements RobotService {
@Autowired
RobotProperties robotProperties;
@Override
public String sayHello() {
return "我是机器人【"+robotProperties.getName()+"】,使用底层大模型:【"+robotProperties.getModel()+"】;我们开始聊天吧";
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
RobotProperties类
@Data
@Component
@ConfigurationProperties(prefix = "robot")
public class RobotProperties {
private String name;
private String model;
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
RobotAutoConfiguration类
@Configuration
@EnableConfigurationProperties(RobotProperties.class)
public class RobotAutoConfiguration {
@Bean
public RobotController robotController(){
return new RobotController();
}
@Bean
public RobotService robotService(){
return new RobotServiceImpl();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
# 项目引用
其他项目引用封装好的功能有三种方式
- @Import(RobotAutoConfiguration.class) 导入封装项目的自动配置类
- 注解方式 @EnableRobot 使用注解方式启用
- 配置文件方式 resources目录下新建META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports文件配置Robot模块的自动配置类 (推荐)
# @Import
@Import(RobotAutoConfiguration.class)
@SpringBootApplication
public class SpringbootHelloApplication {
public static void main(String[] args) {
}
}
1
2
3
4
5
6
2
3
4
5
6
# 注解方式
@EnableRobot
@SpringBootApplication
public class SpringbootHelloApplication {
public static void main(String[] args) {
}
}
1
2
3
4
5
6
2
3
4
5
6
# 配置文件方式 (推荐)
resources目录下新建META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports文件配置Robot模块的自动配置类
com.zhou.robot.start.config.RobotAutoConfiguration
1
Last Updated: 2025/10/22, 08:25:28