【发布时间】:2017-04-25 10:49:59
【问题描述】:
我正在尝试将一个 bean 依赖注入到另一个中,但我想通过简单地直接自动装配到类中来做到这一点,而不是通过“@Configuration 类”。这是控制器类:
@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)
}
}
然而,当我像这样设置依赖注入时,我得到一个空指针异常,因为自动装配的 bean“requestServiceConfig”没有被实例化。如何通过自动装配依赖注入 bean,这样我就不必通过构造函数传递对 bean 的引用?
【问题讨论】:
-
NPE 从何而来?
if (requestServiceConfig.getType() == 'rest'){行? -
"type" 是 ServiceModel 类中的一个字段。 “requestServiceConfig”是该类的一个实例。这是 groovy 代码,所以我不需要使用“.equals”方法。
标签: java spring web-services spring-mvc