我知道我可以使用@Autowired 在类中注入(inject)一个bean。
现在我很好奇:: 我不想拥有 @Autowired 的私有(private)属性。 我的 Controller 中有一个函数,我想直接在函数中注入(inject) bean 作为参数。 我收到一条错误消息,指出文件和 token 不是 beans。
有没有办法 Autowiring 或注入(inject)我需要的 bean 作为参数?
@Controller
public class SpinalToolboxWebController {
/*@Autowired
private FileOperationsService fileOperationsService;
@Autowired
private Comparator<String> comparator;
@Autowired
private ServerResponse serverResponse;
@Autowired
private SoftwareCommunicationService softwareCommunicationService;
@Autowired
private StringBuffer stringBuffer;
@Autowired
private UserEnvironmentService userEnvironmentService;*/
@Autowired
@RequestMapping(value="/upload", method = RequestMethod.POST, produces="application/json")
public @ResponseBody
ServerResponse handleUploadedFiles(@RequestParam(value = "file") MultipartFile file,
@RequestParam(value="token") String token,
SoftwareCommunicationService softwareCommunicationService,
FileOperationsService fileOperationsService,
ServerResponse serverResponse )throws IOException {
System.out.println("Passing throught upload controller");
if(!fileOperationsService.isUploadedFileExtensionAllowed(file.getOriginalFilename()))
{
serverResponse.setUndefinedResponse();
return serverResponse;
}
if(fileOperationsService.uploadFile(file, token)){
serverResponse.setResponse(file, softwareCommunicationService.generateRawAndHeader(file));
}
else{
serverResponse.setUndefinedResponse();
}
return serverResponse;
}
}
最佳答案
作为内置功能,没有。你不能按照你的建议去做。
然而,Spring 提供了您可以自行编程此功能的工具。您需要提出一个标记注释类型。类似 @MethodBean
。您可以注释要从 ApplicationContext
注入(inject)的处理程序方法参数。 。然后,您需要编写一个扩展 HandlerMethodArgumentResolver
的类并查找此注释。您必须添加@Autowired
WebApplicationContext
从中获取 bean 并将它们提供给方法的字段。
然后您可以将此 bean 注册为 HandlerMethodArgumentResolver
的一部分我们的 MVC 堆栈的 s。
当 Spring 确定它必须调用示例中的处理程序方法时,现在看起来像这样
@RequestMapping(value="/upload", method = RequestMethod.POST, produces="application/json")
public @ResponseBody
ServerResponse handleUploadedFiles(@RequestParam(value = "file") MultipartFile file,
@RequestParam(value="token") String token,
@MethodBean SoftwareCommunicationService softwareCommunicationService,
@MethodBean FileOperationsService fileOperationsService,
@MethodBean ServerResponse serverResponse )throws IOException {
它将使用适当的HandlerMethodArgumentResolver
解析每个参数的参数。
对于@MethodBean
带注释的参数,它会找到你的自定义实现,在注入(inject)的WebApplicationContext
中查找参数类型的bean ,并将其作为参数提供。
关于java - 将特定 bean 作为参数注入(inject)具有多个参数的函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27305881/