自定义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
假设我们要做一个“通知中心”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设计成“开箱即用”的模块,前端无需关心实现细节,只关注接口调用和响应处理。