gpt4 book ai didi

java - Spring Boot 使用请求范围的 bean 进行依赖注入(inject)

转载 作者:太空宇宙 更新时间:2023-11-04 11:59:23 26 4
gpt4 key购买 nike

我正在尝试将一个bean依赖注入(inject)到另一个bean中,但我想通过简单地直接 Autowiring 到类中来实现这一点,而不是通过“@Configuration类”。这是 Controller 类:

@Controller
public class RestfulSourceController {

@Autowired
Response response;

@RequestMapping(value="/rest", method=RequestMethod.GET, produces="application/json")
@ResponseBody
public Object greeting() {
return response.getResponse();
}

}

这里是“@Configuration”类,每个类中都声明了一个 bean

@Configuration
class RequestConfigurationBeans {

@Autowired
private ServicesRepository servicesRepo;

@Autowired
private HttpServletRequest request;

@Bean(name = 'requestServiceConfig')
@Scope(value=WebApplicationContext.SCOPE_REQUEST, proxyMode=ScopedProxyMode.TARGET_CLASS)
public ServiceModel requestServiceConfig(){
String serviceName = RequestUtil.getServiceName(this.request)
ServiceModel serviceModel = servicesRepo.findByName(serviceName)
return serviceModel
}

}

@Configuration
public class ServletFilterBeans {

/* I don't want to autowire here, instead I want to autowire in the Response class directly, instead of passing the bean reference into the constructor
@Autowired
ServiceModel requestServiceConfig
*/

@Bean
@Scope(value=WebApplicationContext.SCOPE_REQUEST, proxyMode=ScopedProxyMode.TARGET_CLASS)
public Response response(){
return new Response(/*requestServiceConfig*/);
}

}

最后是 Response 类:

class Response {

//I want to Autowire the bean instead of passing the reference to the constructor
@Autowired
ServiceModel requestServiceConfig

Object response

public Response(/*ServiceModel requestServiceConfig*/){
//this.requestServiceConfig = requestServiceConfig

if (requestServiceConfig.getType() == 'rest'){
this.response = getRestfulSource()
}

}


private Object getRestfulSource(){
RestTemplate restTemplate = new RestTemplate()
String url = requestServiceConfig.sourceInfo.get('url')
return restTemplate.getForObject(url, Object.class)
}
}

但是,当我像这样设置依赖注入(inject)时,我收到一个空指针异常,因为 Autowiring 的 bean“requestServiceConfig”未实例化。如何使用 Autowiring 来依赖注入(inject) bean,这样我就不必通过构造函数传递对 bean 的引用?

最佳答案

问题是在 Response 的构造函数中使用了 requestServiceConfig。 Autowiring 只能在对象创建后发生,因此这里的依赖关系只能为空。

要解决问题并能够使用 Autowiring ,您可以将代码从构造函数移动到 @PostConstruct 生命周期方法:

@PostConstruct
private void init() {
if ("rest".equals(this.requestServiceConfig.getType())) {
this.response = getRestfulSource();
}
}

关于java - Spring Boot 使用请求范围的 bean 进行依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41069214/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com