我有以下类,其中包含带有 @NotEmpty 注释的 errorRequests。
public class ErrorsRequests implements Serializable {
private static final long serialVersionUID = -727308651190295062L;
private String applicationName;
@NotEmpty
@Valid
@JsonProperty("errors")
private List<ErrorsRequest> errorRequests;
Run Code Online (Sandbox Code Playgroud)
我的控制器如下所示:
@Autowired
@Qualifier("errorStreamValidator")
private Validator errorStreamValidator;
@RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE,
consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Void> errorReporting(@NotNull @PathVariable String applicationName,
@Valid @NotNull @RequestBody ErrorsRequests errorsRequests, BindingResult results) {
Run Code Online (Sandbox Code Playgroud)
我的类路径中有所需的休眠验证器类。
当我输入以下 JSON 时:
{
"errorss": [
]
}
Run Code Online (Sandbox Code Playgroud)
@NotEmpty 验证根本没有启动。Hibernate 验证仅在 json 中包含错误元素时才有效,如下所示
{
"errors": [
]
}
Run Code Online (Sandbox Code Playgroud)
我可以让第一个案例也起作用吗?
spring-mvc hibernate-validator jackson spring-restcontroller
我使用Spring Boot。
在 REST 控制器中,当我们使用注释为字符串参数@RequestParam设置默认值时,有没有办法?null
我的 Spring RestController 中有以下方法:
@RequestMapping(value = "/{decisionId}", method = RequestMethod.GET)
public DecisionResponse findById(@PathVariable @NotNull @DecimalMin("0") Long decisionId) {
....
}
Run Code Online (Sandbox Code Playgroud)
现在我需要添加通过{decisionIds}以下方式找到一组 DecisionResponse 的可能性:
@RequestMapping(value = "/{decisionIds}", method = RequestMethod.GET)
public List<DecisionResponse> findByIds(@PathVariable @NotNull @DecimalMin("0") Set<Long> decisionIds) {
....
}
Run Code Online (Sandbox Code Playgroud)
以下两种方法不能同时使用。
实现此功能的正确方法是什么?{decisionIds}即使我只需要 1 个Decision对象,我是否应该只留下一个等待并返回集合的方法(第二个) ?还有另一种正确的方法来实现这个吗?
我正在尝试实现 Rest Api,代码看起来正确且简单,但我收到此错误,并且无法找出问题所在。

日志输出以下内容。
2017-10-10 14:49:40.946 警告 5750 --- [nio-8080-exec-4] osweb.servlet.PageNotFound:不支持请求方法“GET”
@RestController("/report")
@CrossOrigin(origins = { "http://localhost:4200" })
public class JasperController {
@RequestMapping(value = "/allReports", method = { RequestMethod.GET }, produces = "application/json")
public String allReport() {
return "allReports!!!";
}
@RequestMapping(value = "/supportedFields", method = { RequestMethod.GET }, produces = "application/json")
public List<String> supportedFields() {
return Arrays.asList("name", "age", "address", "code", "contract");
}
}
Run Code Online (Sandbox Code Playgroud) 我在 RestController 类中自动装配了 ApplicationContext,因为我需要为收到的每个请求创建一个原型 bean。
为了创建 bean,我尝试了 context.getBean(xx) 但 context 没有列出 getBean() 方法。有没有办法可以在 RestController 类中获取原型类的 bean。我将此应用程序作为 Spring boot 运行。
示例代码在这里:
@RestController
@RequestMapping("/Restcompare")
public class CompareService {
@Autowired
private ApplicationContext context;
private Comparator comparator;
@RequestMapping("/compare")
public String vcompare(@RequestParam(value="pre", defaultValue="")
String pre, @RequestParam(value="post", defaultValue="") String post){
comparator = context.getBean(Comparator.class); //Error here
}
}
Run Code Online (Sandbox Code Playgroud)
更新:
解决方案: IDE 不知何故导入了 Spring 框架之外的不同 ApplicationContext。更正导入以org.springframework.context.ApplicationContext解决问题。
spring spring-ioc spring-boot spring-restcontroller spring-rest
我在 Spring Boot 中遇到这个奇怪的问题,@Cacheable它在控制器中工作,但不在服务内部工作。我可以在 Redis 中看到 GET 调用,但看不到 PUT 调用。
这是有效的,因为它位于控制器内部
@RestController
@RequestMapping(value="/places")
public class PlacesController {
private AwesomeService awesomeService;
@Autowired
public PlacesController(AwesomeService awesomeService) {
this.awesomeService = awesomeService;
}
@GetMapping(value = "/search")
@Cacheable(value = "com.example.webservice.controller.PlacesController", key = "#query", unless = "#result != null")
public Result search(@RequestParam(value = "query") String query) {
return this.awesomeService.queryAutoComplete(query);
}
}
Run Code Online (Sandbox Code Playgroud)
但是@Cacheable当我在服务中这样做时不起作用
@Service
public class AwesomeApi {
private final RestTemplate restTemplate = new RestTemplate();
@Cacheable(value = "com.example.webservice.api.AwesomeApi", key = "#query", unless = …Run Code Online (Sandbox Code Playgroud) 我有一个文件列表,该列表可能包含重复的文件名,但这些文件驻留在具有不同数据的不同位置。现在,当我尝试在 zip 中添加这些文件时,我收到java.lang.Exception:重复条目: File1.xlsx。请建议我如何添加重复的文件名。一种解决方案是,如果我可以将重复文件重命名为 File , File_1,File_2.. 但我不确定如何实现它。请帮忙 !!!如果所有文件名都是唯一的,下面是我的工作代码。
Resource resource = null;
try (ZipOutputStream zippedOut = new ZipOutputStream(response.getOutputStream())) {
for (String file : fileNames) {
resource = new FileSystemResource(file);
if(!resource.exists() && resource != null) {
ZipEntry e = new ZipEntry(resource.getFilename());
//Configure the zip entry, the properties of the file
e.setSize(resource.contentLength());
e.setTime(System.currentTimeMillis());
// etc.
zippedOut.putNextEntry(e);
//And the content of the resource:
StreamUtils.copy(resource.getInputStream(), zippedOut);
zippedOut.closeEntry();
}
}
//zippedOut.close();
zippedOut.finish();
return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=download.zip").body(zippedOut);
} catch (Exception e) {
throw new …Run Code Online (Sandbox Code Playgroud) 使用 spring 控制器,端点在主体响应中返回文件。我想确保不要使用“尝试使用资源”来避免资源泄漏,但在邮递员中我会收到错误:
“错误”:“内部服务器错误”,“消息”:“流已关闭”,
Spring控制器中的代码片段:
InputStreamResource result;
ResponseEntity<Resource> response;
try(FileInputStream ios = new FileInputStream(file)){
result = new InputStreamResource(ios);
response = ResponseEntity.ok()
.headers(/*some headers here*/)
.contentLength(file.length())
.contentType(/*some media type here*/)
.body(result);
logger.info("successfully created");
return response;
} catch (IOException e) {
//some code here..
}
Run Code Online (Sandbox Code Playgroud)
有趣的是,在日志中我收到了成功消息,但在邮递员或浏览器中(这是一个 GET 请求)我收到了错误。
如果不使用“try-with-resource”,它会起作用,但我担心这种方式会导致资源泄漏。
我在 Java 11 中使用 Spring Boot 2。我有以下实体......
@Data
@Entity
@Table(name = "Users")
public class User implements UserDetails {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private UUID id;
private String firstName;
private String lastName;
@NotBlank(message = "Email is mandatory")
@Column(unique=true)
private String email;
private String password;
private boolean enabled;
private boolean tokenExpired;
@ManyToMany
@JoinTable(
name = "users_roles",
joinColumns = @JoinColumn(
name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(
name = "role_id", referencedColumnName = "id"))
private Collection<Role> roles;
Run Code Online (Sandbox Code Playgroud)
请注意电子邮件列上的唯一约束。当我提交创建请求时,有没有办法配置 Spring Boot 来验证该约束?我有下面的休息控制器......
@RestController …Run Code Online (Sandbox Code Playgroud) 我检查了所有类似的帖子,但仍然找不到解决方案。
问题是测试类中不存在必需的请求部分“文件” 。
我想上传一个文件并将其保存到数据库中。这是我的休息控制器@RestController:
@PostMapping(value = "/upload")
public ResponseEntity<LogoDto> uploadLogo(@RequestParam("file") MultipartFile multipartFile) {
return ResponseEntity.ok(logoService.createLogo(multipartFile));
}
Run Code Online (Sandbox Code Playgroud)
和我的测试课:
@Test
public void createLogo2() throws Exception {
String toJsonLogoDto = new Gson().toJson(logoDto);
MockMultipartFile file = new MockMultipartFile("path", "url", MediaType.APPLICATION_JSON_VALUE, image);
LogoDto response = LogoDataTest.validLogoDto();
Mockito.when(logoServiceMock.createLogo(Mockito.any(MultipartFile.class))).thenReturn(response);
mockMvc.perform(MockMvcRequestBuilders.multipart("/brand-icon/upload")
.file(file)
.content(MediaType.APPLICATION_JSON_VALUE)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.characterEncoding(CharEncoding.UTF_8))
.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.status().isOk());
}
Run Code Online (Sandbox Code Playgroud)
我的application.yml看起来像这样:
spring:
servlet:
multipart:
enabled: true
max-file-size: 2MB
max-request-size: 10MB
Run Code Online (Sandbox Code Playgroud)
我尝试在我的@PostMapping中添加消耗;尝试设置每个 MediaTypes.. 仍然会出现错误。
我感谢您的所有回答。
spring spring-mvc spring-boot spring-restcontroller spring-rest
spring ×7
spring-boot ×5
java ×3
spring-mvc ×3
spring-rest ×2
annotations ×1
jackson ×1
redis ×1
rest ×1
spring-cache ×1
spring-ioc ×1
stream ×1