Spring Data JPA中@Value注入跨域配置引发依赖异常问题
问题分析与解决方案
咱们先拆解下你遇到的核心问题,一步步来解决:
1. 跨域配置的错误用法
你在application.properties里把@CrossOrigin注解直接作为配置值,这是完全不对的——配置文件只能存放字符串类型的配置项,不能直接放Spring注解。同时,你在AccountController里把@Value标注在请求方法上,这也是错误的用法:@Value是用来给字段或方法参数注入配置值的,不能直接贴在请求处理方法上。
2. 启动报错的直接原因
控制台的错误提到btnSaveClick方法的参数无法转换类型,这大概率是因为错误的@Value用法干扰了Spring的依赖注入逻辑,导致容器无法正确创建AccountController实例。
正确的实现步骤
第一步:修正application.properties配置
把跨域允许的源地址单独抽出来作为配置项,去掉注解内容:
# 跨域允许的源地址 crossOrigin.origins=http://localhost:4200 server.port=8086 spring.datasource.url=jdbc:postgresql://localhost/SpaceStudyDB spring.datasource.username=postgres spring.datasource.password=postgres
第二步:在Controller里正确配置跨域
有两种方式,根据你的需求选择:
方式一:给整个Controller的所有接口开启跨域
在Controller类上添加@CrossOrigin,并引用配置项:
@RestController @RequestMapping("/api.spacestudy.com/SpaceStudy/Admin/Account") @CrossOrigin(origins = "${crossOrigin.origins}") // 整个类的接口都允许指定源跨域 public class AccountController { @Autowired AccountService accService; @GetMapping("/loadAcctLocationList") public ResponseEntity<List<Account>> findLocation() { return ResponseEntity.ok(accService.findLocation()); } // 其他接口方法... }
方式二:仅给特定接口开启跨域
在需要跨域的方法上单独添加@CrossOrigin:
@RestController @RequestMapping("/api.spacestudy.com/SpaceStudy/Admin/Account") public class AccountController { @Autowired AccountService accService; @GetMapping("/loadAcctLocationList") @CrossOrigin(origins = "${crossOrigin.origins}") // 仅该接口允许跨域 public ResponseEntity<List<Account>> findLocation() { return ResponseEntity.ok(accService.findLocation()); } // 其他接口方法... }
第三步:修正测试类的请求路径
你的测试类里请求路径和Controller的@RequestMapping不匹配,会导致测试失败。Controller的根路径是/api.spacestudy.com/SpaceStudy/Admin/Account,所以测试里的请求路径应该调整为:
mockMvc.perform(get("/api.spacestudy.com/SpaceStudy/Admin/Account/loadAcctLocationList"))
这样调整后,Spring容器就能正常启动,跨域配置也能生效,测试也能正确命中接口了。
内容的提问来源于stack exchange,提问作者SpringUser
相关产品推荐
相关产品推荐

