【发布时间】:2021-02-07 14:16:20
【问题描述】:
我创建了一个服务类,TestService,它的构造函数接受一个字符串数组,并有一点逻辑来返回一个长度大于 5 的字符串列表。
如何使用 Strings 参数数组将其注入到我的 Controller 类中?
@RestController
public class Controller {
private final TestService testService;
@Autowired
public Controller(TestService testService) {
this.testService = testService;
}
@PostMapping("test")
public List<String> test(@RequestBody TestDTO request) {
String[] testStrings = request.getTestStrings();
// I want to run testService.getStringsOverLength5() on testStrings
List<String> strings = testService.getStringsOverLength5();
return strings;
}
}
@Service
public class TestService {
private final String[] testStrings;
public TestService(String[] testStrings) {
this.testStrings = testStrings;
}
public List<String> getStringsOverLength5() {
return Arrays.stream(testStrings)
.filter(s -> s.length() > 5)
.collect(Collectors.toList());
}
}
public class TestDTO {
private String[] testStrings;
public TestDTO() {}
public String[] getTestStrings() {
return testStrings;
}
public void setTestStrings(String[] testStrings) {
this.testStrings = testStrings;
}
}
【问题讨论】:
-
有一个
@Bean,它返回String[]
标签: java spring-boot dependency-injection constructor