带有构造函数参数的java Spring自动关联依赖项
我创建了一个服务类TestService,它的构造函数接受一个字符串数组,并有一个小逻辑来返回长度大于5的字符串列表
如何使用字符串数组参数将其注入控制器类
@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;
}
}
# 1 楼答案
String
或String[]
不是bean类,因此不能使用构造函数Autowired
来实现。但是你可以像下面那样使用SetterAutowired
# 2 楼答案
我认为这是不可能的。而是注入
String[] testStrings
持有者:然而,在本例中,似乎最好将
testStrings
作为getStringsOverLength5
方法参数传递