自定义 Starter封装 后端通用功能并暴露 REST接口 ,js 通过 http 请求调用这些接口实现协作。1. 创建 Starter 模块,包含自动配置类、属性类和服务类;2. 在主应用引入 Starter 依赖并配置参数;3. 编写 Controller 暴露 API;4. 前端 使用 fetch 等方法发送请求获取响应。关键在于前后端分离职责,Starter 开箱即用,前端专注接口调用与数据处理,需配置 CORS 确保跨域访问正常。

JS 与 spring Boot 自定义 Starter 的配合,本质上是 前端 与后端模块化服务的协作。spring boot自定义 Starter 用于封装后端通用功能(如日志、权限、消息推送等),供多个项目快速引入。而 javaScript(通常运行在浏览器或 Node.js 环境)作为前端技术,通过 HTTP 请求与这些 Starter 提供的接口进行交互。下面说明如何实现两者的有效配合。
理解自定义 Starter 的作用
自定义 Starter 是一个可复用的自动配置模块,它将一组功能打包,简化其他 Spring Boot 项目的集成流程。例如你开发了一个短信发送功能的 Starter,项目只需引入该依赖并配置参数,即可使用短信服务。
关键点:
- Starter 不直接处理前端逻辑,而是暴露 REST API 或 websocket 等接口
- JS 通过调用这些接口来使用 Starter 封装的功能
- Starter 内部可包含自动配置、默认参数、健康检查等机制
创建一个简单的自定义 Starter
假设我们要做一个“通知中心”Starter,支持发送提示信息。
1. 创建 starter 模块结构
新建 maven 项目:notification-spring-boot-starter
2. 添加自动配置类
创建 NotificationAutoConfiguration.java
“`java @Configuration @EnableConfigurationProperties(NotificationProperties.class) @ConditionalOnProperty(prefix = “notification”, name = “enabled”, havingValue = “true”) public class NotificationAutoConfiguration {
@Bean public NotificationService notificationService() { return new NotificationService(); }
}
<font color="#0066cc">3. 定义配置属性 </font> ```java @ConfigurationProperties("notification") public class NotificationProperties {private boolean enabled = true; private String defaultUser = "admin"; // getter 和 setter }
4. 提供业务服务
@Service public class NotificationService {public String send(String msg) {return "[OK] Sent to user: " + msg; } }
5. 配置 spring.factories 在 src/main/resources/META-INF/spring.factories 中添加:
org.springframework.boot.autoconfigure.EnableAutoConfiguration= com.example.NotificationAutoConfiguration
在主应用中启用 Starter 功能
在你的 Spring Boot 主项目中引入该 Starter 依赖(可发布到本地或私有仓库):
“`xml
添加配置 application.yml:
“`yaml notification: enabled: true default-user: zhangsan “`
编写 Controller 暴露接口:
“`java @RestController @RequestMapping(“/api/notification”) public class NotificationController {
@Autowired private NotificationService service; @GetMapping("/send") public Map<String, Object> send(@RequestParam String msg) {Map<String, Object> result = new HashMap<>(); result.put("status", "success"); result.put("data", service.send(msg)); return result; }
}
<H3> 前端 JS 调用 Starter 提供的接口 </H3> <p> 前端使用原生 JS 或框架(如vue、react)发起请求即可。</p> <font color="#0066cc"> 示例:使用 fetch 发送请求 </font> ```javascript fetch('/api/notification/send?msg=HelloWorld') .then(response => response.json()) .then(data => { console.log('通知发送成功:', data); }) .catch(err => { console.error('发送失败:', err); });
注意事项:
- 确保后端启用 CORS,允许前端域名访问(可通过配置 WebMvcConfigurer 实现)
- 接口路径要与 Controller 映射一致
- 建议使用 JSON 格式传递数据,便于前后端解析
基本上就这些。Starter 封装了后端能力,JS 通过标准 HTTP 通信使用这些能力,两者职责分明,协同高效。关键是把 Starter 设计成“开箱即用”的模块,前端无需关心实现细节,只关注接口调用和响应处理。